To use the above classes of the fstream library, you must include it in your program as a header file. Of course, you will use the include preprocessor directive. You must also include the iostream header file. Before performing any operation on a file, you must first open it. If you need to write to the file, open it using fstream or ofstream objects. If you only need to read from the file, open it using the ifstream object. The three objects, that is, fstream, ofstream, and ifstream, have the open function defined in them.
The function takes this syntax:. Code Explanation:. The fstream, ofstream, and ifstream objects have the close function for closing files. Data is added to the end of the file. If is opened successfully fopen loads it into memory and sets up a pointer which points to the first character in it.
Returns NULL, if unable to open the file. If the file is opened successfully fopen loads it into memory and sets up a pointer which points to the last character in it. For performing the operations on the file, a special pointer called File pointer is used which is declared as. Skip to content. Change Language. Related Articles. Table of Contents. Improve Article. Save Article. Like Article. Take a step-up from those "Hello World" programs.
We can read content of a file in c using the fscanf and fgets and fgetc functions. All are used to read contents of a file. The fscanf function is used to read character set i. It returns the EOF, when all the content of the file are read by it. The fgetc function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file. We can write data to a file in C using the fprintf , fputs , fputc functions.
All are used to write contents to a file. The fputf function in C can be used to write to a file. It is used to write a line character line to the file. The fclose function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it.
0コメント