How to Read From File in C
C File I/O and Binary File I/O
By Alex Allain
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 y'all need to use a FILE arrow, which will allow the plan go on rails of the file being accessed. (You lot can call up of it as the memory address of the file or the location of the file).
For example:
FILE *fp;
fopen
To open a file you need to utilize the fopen function, which returns a FILE pointer. Once you lot've opened a file, you lot can utilize the FILE pointer to let the compiler perform input and output functions on the file.
FILE *fopen(const char *filename, const char *mode);
In the filename, if yous use a string literal equally the argument, you lot demand to remember to use double backslashes rather than a single backslash as you otherwise take a chance an escape character such equally \t. Using double backslashes \\ escapes the \ central, so the string works as information technology is expected. Your users, of course, do not demand to exercise this! It'due south just the style quoted strings are handled in C and C++.
fopen modes
The allowed modes for fopen are equally follows:
r - open up for reading w - open for writing (file demand not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at commencement w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)
Note that information technology's possible for fopen to fail fifty-fifty if your plan is perfectly right: you might try to open a file specified by the user, and that file might non be (or it might be write-protected). In those cases, fopen will render 0, the NULL arrow.
Hither's a simple example of using fopen:
FILE *fp; fp=fopen("c:\\test.txt", "r");
This code will open test.txt for reading in text fashion. To open a file in a binary mode yous 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 lot should close information technology using the function
int fclose(FILE *a_file);
fclose returns zero if the file is closed successfully.
An example of fclose is
fclose(fp);
Reading and writing with fprintf, fscanf fputc, and fgetc
To work with text input and output, you apply fprintf and fscanf, both of which are similar to their friends printf and scanf except that yous must pass the FILE pointer as first argument. For case:
FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n");
Information technology is also possible to read (or write) a unmarried character at a time--this can be useful if you wish to perform grapheme-past-character input (for instance, if you lot need to keep rail of every piece of punctuation in a file it would make more sense to read in a single character than to read in a cord at a fourth dimension.) The fgetc office, which takes a file pointer, and returns an int, will let yous read a unmarried grapheme from a file:
int fgetc (FILE *fp);
Find that fgetc returns an int. What this actually ways is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other mitt, when you're at the very end of the file, you can't become a character value--in this case, fgetc will return "EOF", which is a constant that indicates that you've reached the cease of the file. To see a full example using fgetc in practice, take a look at the example here.
The fputc function allows you to write a graphic symbol at a fourth dimension--you might notice this useful if y'all wanted to copy a file character by graphic symbol. It looks like this:
int fputc( int c, FILE *fp );
Notation that the first statement should be in the range of an unsigned char so that 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, information technology volition 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:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
Both of these functions deal with blocks of memories - normally 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 wait at i function to see how the note works.
fread takes four arguments. Don't be confused past the declaration of a void *ptr; void ways that it is a pointer that can be used for whatsoever type variable. The beginning argument is the name of the array or the accost of the construction you desire to write to the file. The second argument is the size of each element of the array; it is in bytes. For instance, if you have an array of characters, you lot would want to read it in one byte chunks, and then size_of_elements is one. You tin can use the sizeof operator to get the size of the various datatypes; for case, if you have a variable int ten; you tin get the size of ten with sizeof(x);. This usage works even for structs or arrays. East.one thousand., if you lot accept a variable of a struct type with the proper name a_struct, you can use sizeof(a_struct) to find out how much memory it is taking up.
e.g.,
sizeof(int);
The 3rd argument is simply how many elements you want to read or write; for example, if you laissez passer a 100 element assortment, yous want to read no more than 100 elements, so you pass in 100.
The final argument is but the file pointer we've been using. When fread is used, after being passed an assortment, 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 instance, is but 30 bytes, only y'all try to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was reached, utilize the feof function, which accepts a FILE arrow and returns true if the end of the file has been reached.
fwrite is similar in usage, except instead of reading into the retentiveness y'all write from memory into a file.
For example,
FILE *fp; fp=fopen("c:\\test.bin", "wb"); char 10[10]="ABCDEFGHIJ"; fwrite(x, sizeof(10[0]), sizeof(10)/sizeof(10[0]), fp);
Quiz yourself
Previous: Strings
Next: Typecasting
Dorsum to C Tutorial Index
Related articles
More on working with files in C
C++ file IO
Source: https://www.cprogramming.com/tutorial/cfileio.html
0 Response to "How to Read From File in C"
Post a Comment