关于c/c++的文件IO整理
FILE create and write
c style
using file descriptor direactly, open, write, close function work together to finish the file operation. Attention that for the file permission part, don’t forget the 0 before 644.
//using file descriptor |
file pointer could be used based on the file descriptor, for the following example, the file descriptor could be transformed into the file pointer point to a FILE struct. On the other hand, the function int fileno(FILE *stream)
could be used to tranform a FILE pointer into a file descriptor. Compared with the file descriptor(only a int number) file pointer contains more info about the file.
#include <stdio.h> |
Or we could use fopen to return a file descriptor direactly.
//using file pointer |
compared with open and write, it is much simple to use fopen and fprintf direactly. for the mode of openning file , refer this (https://www.tutorialspoint.com/cprogramming/c_file_io.htm)
c++ style
//using fstream |
FILE load
read the content of the file into the program, the load operation could be diveided into several types by the granularity, load by specific bytes, load line by line, and load the total files at once.
one important issue is data over flow during file reading.
the first step is always using fopen to return the File pointer. Similar to open/read/write(system call for unix), we could use fopen, fread, fwrite(library with the internal buffer for c language). I think open/read/write are much low level for practical using, in real use case, I prefer to use fopen, fread, fwrite.
- for fread, the input could be controled by number of bytes,
- for fgets, the content could be loaded by every line automatically, it will finish reading till the endle or
\n
. - there is another function
gets
which could also load every line once, but there is no protection for buffer for this function. gets and scanf are not secure way for input operation.
refer this (https://stackoverflow.com/questions/18253413/difference-between-fgets-and-fread) for the difference of two functions.
from the prospect of programming, fgets is much simple to use.(refer this https://blog.csdn.net/lanceleng/article/details/8730192 for more info)
another thing is the difference between scanf
and fscanf
, scanf could load info from stdin and fscanf could load info from file stream. We could also use freopen("in.txt","r",stdin)
to redirect the stream from file into stdin if we want to use scanf instead of the fscanf.
#include <stdio.h> |
string loadFile(char *filename)
{
ifstream ifs;
ifs.open(filename);
if (ifs.fail())
{
printf("ifs fail\n");
exit(1);
}
string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
```
reference
https://courses.cs.washington.edu/courses/cse373/99au/assignments/fileIO.html
fopen mode