In this tutorial, you will learn to work with arrays. You will learn to declare, initialize and access array elements of an array with the help of examples. An array is a variable that can store multiple values. The using keyword has three major uses: The using statement defines a scope at the end of which an object will be disposed. The using directive creates an alias for a namespace or imports types defined in other namespaces. The using static directive imports the members of a single class.
In this tutorial, you'll learn how to do file IO, text and binary, in C, using fopen, fwrite, and fread, fprintf, fscanf, fgetc and fputc.
FILE *
For C File I/O you need to use a FILE pointer, which will let the programkeep track of the file being accessed. (You can think of it as the memoryaddress of the file or the location of the file).
For example:
fopen
To open a file you need to use the fopen function, which returns a FILE pointer. Once you've opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as t. Using double backslashes escapes the key, so the string works as it is expected. Your users, of course, do not need to do this! It's just the way quoted strings are handled in C and C++.
fopen modes
The allowed modes for fopen are as follows: Note that it's possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer.Here's a simple example of using fopen:
This code will open test.txt for reading in text mode. To open a file in a binary mode you must add a b to the end of the mode string; for example, 'rb' (for the reading and writing modes, you can add the b either after the plus sign - 'r+b' - or before - 'rb+')
fclose
When you're done working with a file, you should close it using the functionfclose returns zero if the file is closed successfully.
An example of fclose is
Reading and writing with fprintf, fscanf fputc, and fgetc
To work with text input and output, you use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. For example:It is also possible to read (or write) a single character at a time--this canbe useful if you wish to perform character-by-character input (for instance,if you need to keep track of every piece of punctuation in a file it wouldmake more sense to read in a single character than to read in a string at atime.) The fgetc function, which takes a file pointer, and returns an int,will let you read a single character from a file:Notice that fgetc returns an int. What this actually means is that when itreads a normal character in the file, it will return a value suitable forstoring in an unsigned char (basically, a number in the range 0 to 255). Onthe other hand, when you're at the very end of the file, you can't get acharacter value--in this case, fgetc will return 'EOF', which is a constant thatindicates that you've reached the end of the file. To see a full exampleusing fgetc in practice, take a look at the example here.
The fputc function allows you to write a character at a time--you might findthis useful if you wanted to copy a file character by character. It lookslike this:Note that the first argument should be in the range of an unsigned char sothat it is a valid character. The second argument is the file to write to.On success, fputc will return the value c, and on failure, it will return EOF.
Binary file I/O - fread and fwrite
For binary File I/O you use fread and fwrite.The declarations for each are similar: Both of these functions deal with blocks of memories - usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.
Let's look at one function to see how the notation works.
fread takes four arguments. Don't be confused by the declaration of a void *ptr; void means that it is a pointer that can be used for any type variable. The first argument is the name of the array or the address of the structure you want to write to the file. The second argument is the size of each element of the array; it is in bytes. For example, if you have an array of characters, you would want to read it in one byte chunks, so size_of_elements is one. You can use the sizeof operator to get the size of the various datatypes; for example, if you have a variable int x; you can get the size of x with sizeof(x);. This usage works even for structs or arrays. E.g., if you have a variable of a struct type with the name a_struct, you can use sizeof(a_struct) to find out how much memory it is taking up.
e.g.,
The third argument is simply how many elements you want to read or write; for example, if you pass a 100 element array, you want to read no more than 100 elements, so you pass in 100.
The final argument is simply the file pointer we've been using. When fread is used, after being passed an array, fread will read from the file until it has filled the array, and it will return the number of elements actually read. If the file, for example, is only 30 bytes, but you try to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was reached, use the feof function, which accepts a FILE pointer and returns true if the end of the file has been reached.
fwrite is similar in usage, except instead of reading into the memory you write from memory into a file.
For example,
Quiz yourself
Previous: Strings
Next: Typecasting
Back to C Tutorial Index
Related articles
More on working with files in C
C++ file IO
Using Computer
As always, a function is a module of code that takes information in (referring to that information with local symbolic names called parameters), does some computation, and (usually) returns a new piece of information based on the parameter information.
Basic Function Design Pattern
For the basic syntax of a function in C, please refer to the C Function Design Pattern chapter.
Dot C files
Black gaming keyboard and mouse. The 'recipe' for a function (the function's code) is always stored in a '.C' file. In C there can be many functions written in a single file.
Ordering of functions in a file
The order of functions inside a file is arbitrary. It does not matter if you put function one at the top of the file and function two at the bottom, or vice versa.
Caveat: In order for one function to 'see' (use) another function, the 'prototype' of the function must be seen in the file before the usage. If a function uses another function that is textually written above it in the file, then this will automatically be true. If the function uses a function that is 'below it' in a file, then the prototype should occur at the top of the file.. see prototypes below.
A Function Prototype
In C, all functions must be written to return a specific TYPE of information and to take in specific types of data (parameters). This information is communicated to the compiler via a function prototype.
Here is the syntax for the function declaration or Prototype:
A Prototype can occur at the top of a C source code file to describe what the function returns and what it takes (return type and parameter list). When this is the case (occuring at the top of the file), the function prototype should be followed by a semi-colon
The function prototype is also used at the beginning of the code for the function. Thus the prototype can occur twice in a C source code file. When the prototype occurs with the code NO semicolon is used.
The Main Function
In C, the 'main' function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is 'called' by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts.
Examples of C Functions:
Return Type of a C function
Every C function must specify the type of data that is being generated. For example, the max function above returns a value of type 'double'. Inside the function, the line 'return X;' must be found, where X is a value or variable containing a value of the given type.
The return statement
When a line of code in a function that says: 'return X;' is executed, the function 'ends' and no more code in the function is executed. The value of X (or the value in the variable represented by X) becomes the result of the function.
Calling a C function (aka invoke a function)
When one piece of code invokes or calls a function, it is done by the following syntax:
The function name must match exactly the name of the function in the function prototype. The args are a list of values (or variables containing values) that are 'passed' into the function.
The number of args 'passed' into a function must exactly match the number of parameters required for the function. The type of each arg must exactly match the type of each parameter. The return variable type must exactly match the return type of the function.
The 'variable' in the example above must have a type equivalent to the return type of the function. Inside the function, somewhere will be the line 'return X'. The value of X is then copied into the 'variable'.
Parameters in C functions
A Parameter is the symbolic name for 'data' that goes into a function. There are two ways to pass parameters in C: Pass by Value, Pass by Reference.
Pass by Value
Pass by Value, means that a copy of the data is made and stored by way of the name of the parameter. Any changes to the parameter have NO affect on data in the calling function.
Pass by Reference
A reference parameter 'refers' to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable.
There are two ways to make a pass by reference parameter:
ARRAYS
Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array.
The ampersand used in the function prototype.
function ( & parameter_name )
To make a normal parameter into a pass by reference parameter, we use the '& param' notation. The ampersand (&) is the syntax to tell C that any changes made to the parameter also modify the original variable containing the data.
Pass by Value Example:
In C, the default is to pass by value. For example:
Pass by Reference Example:
Warning: C++
I suggest that you use a C++ compiler such as g++ which allows the following pass by reference syntax (a much more modern style). The Syntax is to use the '&' in front of the parameter name in the function declaration. The calling code and usage inside the function are the same as before. For example:
Warning: Standard C - Using 'Pointers'
With standard C you have to put the & in the calling location as opposed to next to the parameter in the function declaration; further, you must use a '*' in the parameter list, and use a '*' whenever using the parameter inside the function.
The '*' is used to define a 'pointer', a discussion of which is beyond the scope of this simple example. Feel free to Google 'Pointers in C' for a long treatise on how to use them.. or take my advice, and (as a beginning programmer) avoid them.
In summary, if you use a reference parameter, any changes to the parameter inside the function are reflected 'outside' of the function (i.e., in the calling function)! If you don't use the & (pass by reference), then we get the same behavior as in Matlab (i.e., the value is changed inside the called function, but maintains its original value in the calling function.
Using Cast Iron On Glass Cooktop
One reason to use reference parameters is to make the program more 'efficient'. Consider passing in a structure as a parameter. If the structure is very big, and we copy all of it, then we are using a lot of unnecessary memory.
Array Parameter Example (ALWAYS pass by reference)
Arrays are always passed by reference in C. They do not use the '&' notation, but are pass by reference none the less. For example:
Constant Reference
To protect from accidentally changing a reference parameter, when we really want it not to be changed (we just want to save time/memory) we can use the C keyword const. For example:
Void Functions
If a function does not return a value, then a special 'TYPE' is used to tell the computer this. The return type is 'void' (all lower case).
Void functions are mostly used in two classes of functions.
The first is a function that prints information for the user to read. For example (for our purposes), the printf function is treated as a void function. (In actuality, printf returns an integer which is the number of characters printed.. but we almost always ignore this value.)
The second use of void functions is with 'reference' parameters (e.g., Arrays). A reference parameter is not a copy of the input data, as is so often the case. A reference parameter is an 'alias' for the same bucket in memory as the input data. Thus any change made to a reference parameter is in fact made to the original variable!