banner



Which Mode Specifier Will Open A File But Will Not Let You Change The File Or Write To It?

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 demand to use a FILE arrow, which volition let the program continue track of the file existence accessed. (Yous tin remember of it as the retentiveness address of the file or the location of the file).

For case:

FILE *fp;

fopen

To open a file y'all need to apply the fopen function, which returns a FILE pointer. Once y'all'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 *mode);

In the filename, if yous utilize a string literal equally the statement, you need to call back to employ double backslashes rather than a single backslash as you otherwise risk an escape character such equally \t. Using double backslashes \\ escapes the \ primal, so the string works as it is expected. Your users, of grade, do non need to practice this! It's just the way quoted strings are handled in C and C++.

fopen modes

The immune modes for fopen are as follows:

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

Note that information technology'south possible for fopen to neglect even if your program is perfectly right: you might try to open up a file specified past the user, and that file might non be (or it might be write-protected). In those cases, fopen volition return 0, the Cypher arrow.

Here'south a simple example of using fopen:

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

This code will open test.txt for reading in text mode. To open up a file in a binary mode you must add a b to the stop of the fashion string; for instance, "rb" (for the reading and writing modes, you tin can add the b either later the plus sign - "r+b" - or before - "rb+")

fclose

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

int fclose(FILE *a_file);

fclose returns zero if the file is airtight successfully.

An instance of fclose is

fclose(fp);

Reading and writing with fprintf, fscanf fputc, and fgetc

To piece of work with text input and output, you utilize fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must laissez passer the FILE pointer as first argument. For example:

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

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

int fgetc (FILE *fp);        

Detect that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it volition return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when yous're at the very finish of the file, you lot tin can't get a character value--in this instance, fgetc will render "EOF", which is a constant that indicates that you've reached the cease of the file. To meet a full example using fgetc in practice, take a await at the example here.

The fputc role allows you to write a character at a fourth dimension--you lot might find this useful if you lot wanted to copy a file character by character. It looks like this:

int fputc( int c, FILE *fp );        

Note that the first argument should exist 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, information technology will return EOF.

Binary file I/O - fread and fwrite

For binary File I/O yous 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 - usually arrays. Because they accept pointers, you lot can also utilise these functions with other information structures; y'all tin can even write structs to a file or a read struct into memory.

Let's look at ane part to see how the notation works.

fread takes four arguments. Don't exist dislocated by the declaration of a void *ptr; void means that it is a pointer that tin can be used for any blazon variable. The first argument is the name of the array or the accost of the construction you want to write to the file. The 2d argument is the size of each element of the array; information technology is in bytes. For example, if you have an array of characters, y'all would want to read it in one byte chunks, so size_of_elements is one. You can use the sizeof operator to get the size of the various datatypes; for example, if you accept a variable int x; you tin get the size of x with sizeof(x);. This usage works fifty-fifty for structs or arrays. Due east.g., if you have a variable of a struct blazon with the name a_struct, you can utilise sizeof(a_struct) to observe out how much retention information technology is taking up.

eastward.one thousand.,

sizeof(int);

The third statement is only how many elements you lot want to read or write; for case, if you laissez passer a 100 element assortment, you want to read no more than 100 elements, so you pass in 100.

The final statement is simply the file pointer nosotros've been using. When fread is used, after beingness passed an array, 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 instance, is only 30 bytes, but you effort to read 100 bytes, it will return that it read thirty bytes. To check to ensure the cease of file was reached, use the feof part, which accepts a FILE pointer and returns true if the end of the file has been reached.

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

For example,

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

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

Related articles

More on working with files in C

C++ file IO

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

Posted by: farmerreanday.blogspot.com

0 Response to "Which Mode Specifier Will Open A File But Will Not Let You Change The File Or Write To It?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel