C Language Learning 010: fopen reading and writing files, language learning fopen
In the input.csv file, we have the following data:
Apple
Pear
Litchis
Pineapple
Watermelon
Now we can read the input.csvfile and write it to the output.csv file. We will use the fopen function.
Function prototype: FILE * fopen (const char * path, const char * mode)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 int main () {
6 char line [80];
7 FILE * in = fopen ("input.csv", "r"); // fopen can create a data stream; r, read
8 FILE * out = fopen ("output.csv", "a"); // a, means append data to a file
9 while (fscanf (in, "% 79 [^ \ n] \ n", line) == 1) {
10 fprintf (out, "from input:% s \ n", line);
11}
12 // After running out of data streams, they need to be closed, even if they will shut themselves down, because usually a process can have a maximum of 256 data streams, the number is limited
13 fclose (in);
14 fclose (out);
15 return 0;
16}
Fopen has many other modes, such
W. Write the file. If the file does not exist, create the file and write it. If the file exists, overwrite the previous data.
There are also a +, w +, r +, and so on, but some compilers do not support it. You can refer to fopen here.