How to Read a File of Numbers in C

C File I/O and Binary File I/O


By Alex Allain

In this tutorial, yous'll learn how to practise 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 volition let the program continue rails of the file being accessed. (You tin think of it as the memory accost of the file or the location of the file).

For case:

FILE *fp;

fopen

To open up a file y'all need to utilize the fopen function, which returns a FILE pointer. Once y'all've opened a file, you can use the FILE pointer to allow the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *style);

In the filename, if you employ a string literal as the statement, you need to think to use double backslashes rather than a single backslash as yous otherwise chance an escape character such equally \t. Using double backslashes \\ escapes the \ key, so the string works as information technology is expected. Your users, of course, practise not need to do this! It's just the mode quoted strings are handled in C and C++.

fopen modes

The allowed modes for fopen are as follows:

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

Note that information technology's possible for fopen to fail even if your programme is perfectly correct: yous might try 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 NULL pointer.

Here'due south a unproblematic example of using fopen:

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

This code will open up exam.txt for reading in text mode. To open a file in a binary manner you must add a b to the finish of the mode cord; for case, "rb" (for the reading and writing modes, you can add the b either after the plus sign - "r+b" - or before - "rb+")

fclose

When yous're done working with a file, you should close information technology using the function

int fclose(FILE *a_file);

fclose returns naught 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, yous use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must pass the FILE arrow as first statement. For example:

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

Information technology is also possible to read (or write) a single character at a time--this can exist useful if y'all wish to perform character-by-grapheme input (for case, if you need to keep runway of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc part, which takes a file pointer, and returns an int, will allow y'all read a single character from a file:

int fgetc (FILE *fp);        

Notice that fgetc returns an int. What this actually means is that when it reads a normal graphic symbol in the file, information technology will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other manus, when you're at the very end of the file, yous can't get a character value--in this case, fgetc will return "EOF", which is a constant that indicates that yous've reached the end of the file. To see a total example using fgetc in practice, take a look at the example here.

The fputc role allows y'all to write a character at a time--yous might find this useful if you wanted to copy a file character by character. It looks like this:

int fputc( int c, FILE *fp );        

Note that the starting time argument should be in the range of an unsigned char so that information technology is a valid character. The 2nd statement 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 yous utilise 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 bargain with blocks of memories - usually arrays. Because they take pointers, you lot can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.

Allow'southward look at one function to see how the notation works.

fread takes iv arguments. Don't exist dislocated by the proclamation of a void *ptr; void means that it is a pointer that tin can be used for whatsoever blazon variable. The first argument is the proper name of the assortment or the address of the structure y'all want to write to the file. The 2d argument is the size of each chemical element of the array; it is in bytes. For case, 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 apply the sizeof operator to get the size of the diverse datatypes; for instance, if yous have a variable int x; yous tin get the size of x with sizeof(x);. This usage works even for structs or arrays. Due east.g., if yous accept a variable of a struct blazon with the proper noun a_struct, you can use sizeof(a_struct) to detect out how much memory it is taking up.

e.g.,

sizeof(int);

The tertiary argument is simply how many elements you want to read or write; for instance, if you pass a 100 chemical element assortment, you lot want to read no more 100 elements, and so you pass in 100.

The last 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 assortment, and it will return the number of elements actually read. If the file, for example, is only 30 bytes, just you try to read 100 bytes, it will return that information technology read 30 bytes. To cheque to ensure the stop of file was reached, utilize the feof part, which accepts a FILE pointer and returns true if the stop of the file has been reached.

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

For example,

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

Quiz yourself
Previous: Strings
Next: Typecasting
Back to C Tutorial Index

Related manufactures

More on working with files in C

C++ file IO

smithdair1961.blogspot.com

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

0 Response to "How to Read a File of Numbers in C"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel