Do You Have to Fopen a File to Read From It C

C File I/O and Binary File I/O


By Alex Allain

In this tutorial, y'all'll acquire 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 volition permit the programme keep rails of the file beingness accessed. (You can retrieve of it as the retention accost of the file or the location of the file).

For case:

FILE *fp;

fopen

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

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

In the filename, if you utilize a string literal as the statement, you need to call back to use double backslashes rather than a single backslash as you lot otherwise chance an escape character such every bit \t. Using double backslashes \\ escapes the \ central, so the string works as it is expected. Your users, of course, exercise not demand to do this! It'south merely the way quoted strings are handled in C and C++.

fopen modes

The allowed modes for fopen are as follows:

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

Annotation that it's possible for fopen to fail even if your plan is perfectly right: 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 Nil pointer.

Here'due south a simple example of using fopen:

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

This code will open test.txt for reading in text style. To open a file in a binary way you must add a b to the cease of the way string; for example, "rb" (for the reading and writing modes, you can add together the b either later on the plus sign - "r+b" - or earlier - "rb+")

fclose

When yous're done working with a file, you should shut it 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 use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must laissez passer the FILE pointer every bit commencement argument. For case:

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

It is too possible to read (or write) a single character at a time--this can be useful if you wish to perform character-by-character input (for case, if yous need to keep rails of every slice of punctuation in a file it would make more sense to read in a unmarried character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, volition permit you lot read a single graphic symbol from a file:

int fgetc (FILE *fp);        

Detect that fgetc returns an int. What this actually means 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 y'all're at the very end of the file, you lot can't become a character value--in this case, fgetc volition return "EOF", which is a abiding that indicates that you've reached the end of the file. To see a full example using fgetc in practise, accept a expect at the example here.

The fputc function allows you to write a graphic symbol at a time--yous might observe this useful if you lot wanted to copy a file graphic symbol past grapheme. It looks like this:

int fputc( int c, FILE *fp );        

Note that the first statement should be in the range of an unsigned char so that it is a valid character. The 2d 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 utilize 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 - unremarkably arrays. Because they have pointers, yous can also use these functions with other data structures; you tin even write structs to a file or a read struct into memory.

Permit'due south expect at one role to encounter how the notation works.

fread takes 4 arguments. Don't be dislocated by the declaration of a void *ptr; void ways that information technology is a pointer that can exist used for any type variable. The first argument is the name of the array or the address of the construction you want to write to the file. The second argument is the size of each element of the assortment; it is in bytes. For example, if you have an array of characters, you would desire to read information technology in one byte chunks, so size_of_elements is one. You can employ the sizeof operator to get the size of the diverse datatypes; for example, if yous have a variable int x; you can go the size of x with sizeof(x);. This usage works fifty-fifty for structs or arrays. Due east.thousand., if you have a variable of a struct blazon with the proper name a_struct, you can use sizeof(a_struct) to find out how much memory information technology is taking up.

e.yard.,

sizeof(int);

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

The last argument is simply 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 volition return the number of elements actually read. If the file, for instance, is just xxx bytes, merely y'all effort to read 100 bytes, it volition return that it read 30 bytes. To check to ensure the finish of file was reached, utilize the feof function, which accepts a FILE pointer and returns truthful if the end of the file has been reached.

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

For example,

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

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

Related articles

More on working with files in C

C++ file IO

bouchardniae1971.blogspot.com

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

0 Response to "Do You Have to Fopen a File to Read From It C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel