Reading Lines From a File in C

C File I/O and Binary File I/O


Past 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 you lot need to use a FILE pointer, which will let the program go along track of the file being accessed. (You can recollect of it as the memory address of the file or the location of the file).

For instance:

FILE *fp;

fopen

To open up a file you need to use the fopen office, which returns a FILE pointer. Once you've opened a file, you lot tin can use 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 need to remember to use double backslashes rather than a unmarried backslash as you otherwise chance an escape grapheme such every bit \t. Using double backslashes \\ escapes the \ fundamental, so the string works as information technology is expected. Your users, of course, practise non need to practice this! Information technology's just the way quoted strings are handled in C and C++.

fopen modes

The allowed modes for fopen are every bit follows:

r  - open for reading westward  - open for writing (file need non be) a  - open up for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open up for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)

Annotation that information technology'due south possible for fopen to fail fifty-fifty if your program is perfectly correct: you lot might endeavour to open up a file specified past the user, and that file might not exist (or information technology might be write-protected). In those cases, fopen will return 0, the Zip pointer.

Here's a simple example of using fopen:

FILE *fp; fp=fopen("c:\\test.txt", "r");

This code volition open up test.txt for reading in text way. To open up a file in a binary mode you must add a b to the end of the mode cord; for case, "rb" (for the reading and writing modes, y'all can add the b either afterwards the plus sign - "r+b" - or before - "rb+")

fclose

When you're done working with a file, you should shut it using the function

int fclose(FILE *a_file);

fclose returns cypher if the file is closed successfully.

An case of fclose is

fclose(fp);

Reading and writing with fprintf, fscanf fputc, and fgetc

To piece of work with text input and output, you use fprintf and fscanf, both of which are like to their friends printf and scanf except that y'all must pass the FILE pointer as commencement argument. For example:

FILE *fp; fp=fopen("c:\\test.txt", "w"); fprintf(fp, "Testing...\n");

It is also possible to read (or write) a single character at a fourth dimension--this can be useful if you wish to perform graphic symbol-by-character input (for instance, if yous demand to keep track of every piece of punctuation in a file it would make more sense to read in a single grapheme than to read in a string at a fourth dimension.) The fgetc part, which takes a file arrow, and returns an int, volition let you read a single character from a file:

int fgetc (FILE *fp);        

Notice that fgetc returns an int. What this actually ways is that when it reads a normal grapheme in the file, it will render a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you're at the very end of the file, you can't go a character value--in this case, fgetc will render "EOF", which is a constant that indicates that you've reached the stop of the file. To see a full instance using fgetc in exercise, take a look at the example here.

The fputc part allows you to write a grapheme at a time--you lot might discover this useful if you wanted to copy a file grapheme by character. It looks like this:

int fputc( int c, FILE *fp );        

Notation that the starting time statement should be in the range of an unsigned char so that information technology is a valid character. The second argument is the file to write to. On success, fputc will render the value c, and on failure, it will return EOF.

Binary file I/O - fread and fwrite

For binary File I/O yous employ fread and fwrite.

The declarations for each are like:

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 - ordinarily arrays. Considering they accept pointers, you tin can also use these functions with other data structures; you tin can even write structs to a file or a read struct into retention.

Allow's look at one part to see how the notation works.

fread takes 4 arguments. Don't be confused by the declaration of a void *ptr; void means that it is a arrow that can be used for any type variable. The first argument is the name of the array or the address of the construction you lot want to write to the file. The second statement is the size of each element of the array; it is in bytes. For instance, if you have an array of characters, you would want to read information technology in one byte chunks, so size_of_elements is one. You can employ the sizeof operator to become the size of the various datatypes; for example, if you accept a variable int x; you can become the size of 10 with sizeof(x);. This usage works even for structs or arrays. E.g., if y'all have a variable of a struct type with the name a_struct, you can utilize sizeof(a_struct) to find out how much retentivity it is taking upward.

due east.g.,

sizeof(int);

The third argument is simply how many elements you want to read or write; for example, if you pass a 100 element array, y'all want to read no more than than 100 elements, and so you laissez passer in 100.

The last argument is simply the file arrow nosotros've been using. When fread is used, after being passed an array, fread will read from the file until it has filled the assortment, and it will render the number of elements actually read. If the file, for instance, 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 terminate of the file has been reached.

fwrite is similar in usage, except instead of reading into the retentiveness you lot write from memory into a file.

For example,

FILE *fp; fp=fopen("c:\\test.bin", "wb"); char 10[10]="ABCDEFGHIJ"; fwrite(ten, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

Quiz yourself
Previous: Strings
Side by side: Typecasting
Back to C Tutorial Index

Related articles

More on working with files in C

C++ file IO

briscoebetimesely.blogspot.com

Source: https://www.cprogramming.com/tutorial/cfileio.html

0 Response to "Reading Lines From a File in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel