Introduction
This tutorial will start with the very basis of File I/O (Input/Output) in C++. After that, I will look into aspects that are more advanced, showing you some tricks, and describing useful functions.
You need to have good understanding of C++, otherwise this tutorial will be unfamiliar and not useful to you!
Your Very First Program
I will first write the code, and after that, I will explain it line by line.
[Read More]
Reading from file or Reading integers from file
#include
#include
#include
#include
using namespace std;
int main() {
int sum = 0;
int x;
ifstream inFile;
inFile.open(“integers.txt”); // read integers from text file
if (!inFile) {
cout « “Unable to open file”;
exit(0); // terminate with error
}
while (inFile » x) {
sum = sum+x;
}
inFile.close();
cout « “Sum = " « sum « endl;
return 0;
}
File Handling in c
/* Program to create a file and write some data the file */
#include
#include
main( )
{
FILE *fp;
char stuff[25];
int index;
fp = fopen(“TENLINES.TXT”,“w”); /* open for writing */
strcpy(stuff,“This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n”, stuff, index);
fclose(fp); /* close the file before ending program */
}
FILE * fopen(char * filename, char * mode)
The mode value in the above example is set to ‘r’, indicating that we want to read from the file.
[Read More]
Error handling
The standard I/O functions maintain two indicators with each open stream to show the end-of-file and error status of the stream. These can be interrogated and set by the following functions:
#include
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);
void perror(const char *s);
Clearerr clears the error and EOF indicators for the stream.
Feof returns non-zero if the stream’s EOF indicator is set, zero otherwise.
Ferror returns non-zero if the stream’s error indicator is set, zero otherwise.
[Read More]
Random access functions
The file I/O routines all work in the same way; unless the user takes explicit steps to change the file position indicator, files will be read and written sequentially. A read followed by a write followed by a read (if the file was opened in a mode to permit that) will cause the second read to start immediately following the end of the data just written. (Remember that stdio insists on the user inserting a buffer-flushing operation between each element of a read-write-read cycle.
[Read More]
File handling in cpp
File I/O with Streams:
Many real-life problems handle large volumes of data, therefore we need to use some devices such as floppy disk or hard disk to store the data.
The data is stored in these devices using the concept of files. A file is a collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these files.
[Read More]