How to Make Cloin Read From Files

C File I/O and Binary File I/O


By Alex Allain

In this tutorial, you lot'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 arrow, which will let the program go on rails of the file being accessed. (You lot tin 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 up a file you need to use the fopen role, which returns a FILE pointer. Once you've opened a file, y'all 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 *way);

In the filename, if yous use a cord literal equally the argument, y'all need to remember to employ double backslashes rather than a single backslash as you lot otherwise risk an escape graphic symbol such as \t. Using double backslashes \\ escapes the \ key, and then the string works as it is expected. Your users, of grade, exercise non 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 every bit follows:

r  - open up for reading westward  - open for writing (file need not exist) a  - open for appending (file need non exist) r+ - open for reading and writing, offset at outset west+ - open up for reading and writing (overwrite file) a+ - open for reading and writing (suspend if file exists)

Annotation that information technology'due south possible for fopen to neglect even if your programme is perfectly correct: you might try to open up a file specified past the user, and that file might non exist (or it 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:\\examination.txt", "r");

This lawmaking will open up test.txt for reading in text style. To open a file in a binary mode you must add a b to the terminate of the manner string; for example, "rb" (for the reading and writing modes, you tin can add the b either after the plus sign - "r+b" - or before - "rb+")

fclose

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

int fclose(FILE *a_file);

fclose returns cypher 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 use fprintf and fscanf, both of which are similar to their friends printf and scanf except that y'all must pass the FILE pointer as first argument. For example:

FILE *fp; fp=fopen("c:\\examination.txt", "due west"); fprintf(fp, "Testing...\n");

It is also possible to read (or write) a single character at a fourth dimension--this tin can exist useful if y'all wish to perform grapheme-past-character input (for example, if you need to keep track of every piece of punctuation in a file it would brand more sense to read in a unmarried character than to read in a string at a time.) The fgetc office, which takes a file pointer, and returns an int, will let you read a unmarried graphic symbol from a file:

int fgetc (FILE *fp);        

Notice that fgetc returns an int. What this actually means is that when it reads a normal grapheme 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 paw, when you're at the very finish of the file, you lot can't go a graphic symbol value--in this instance, fgetc will return "EOF", which is a constant that indicates that you've reached the terminate of the file. To see a full example using fgetc in exercise, take a wait at the example here.

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

int fputc( int c, FILE *fp );        

Annotation that the first argument should be in the range of an unsigned char so that information technology is a valid grapheme. The 2nd statement is the file to write to. On success, fputc will return the value c, and on failure, information technology 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:

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 - commonly arrays. Because they take pointers, yous tin can also apply these functions with other information structures; you lot can even write structs to a file or a read struct into retentiveness.

Let's await at 1 role to run into how the notation works.

fread takes 4 arguments. Don't be confused by the declaration of a void *ptr; void means that information technology is a pointer that can be used for any type variable. The outset argument is the proper noun of the array or the address of the construction you want to write to the file. The second argument is the size of each chemical element of the array; it is in bytes. For example, if you have an array of characters, yous would want to read it in one byte chunks, then size_of_elements is ane. You lot tin employ the sizeof operator to get the size of the various datatypes; for example, if y'all accept a variable int x; you can get the size of ten with sizeof(ten);. This usage works even for structs or arrays. East.k., if you have a variable of a struct type with the name a_struct, y'all can employ sizeof(a_struct) to find out how much memory information technology is taking up.

e.grand.,

sizeof(int);

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

The final argument is simply the file arrow nosotros've been using. When fread is used, after beingness passed an assortment, fread will read from the file until it has filled the array, and information technology will return the number of elements actually read. If the file, for instance, is simply xxx bytes, only yous try to read 100 bytes, information technology will render that it read thirty bytes. To check to ensure the cease of file was reached, apply the feof function, which accepts a FILE pointer and returns truthful if the end 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:\\test.bin", "wb"); char x[ten]="ABCDEFGHIJ"; fwrite(x, sizeof(ten[0]), sizeof(x)/sizeof(x[0]), fp);

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

Related articles

More on working with files in C

C++ file IO

paullmucer1941.blogspot.com

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

0 Response to "How to Make Cloin Read From Files"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel