Linux opens a file and writes a string. Read the information about the corresponding file at the same time
in Linux. Use C language. Use the fopen () function to open a file (if no file exists, create a new one, such as Data/test.dat), at the same time
fwrite () writes the corresponding string to it, each time the input writes are wrapped, and finally the corresponding information is read with Fread ().
the corresponding code such as the following: TEST.c
/*test.c:create a File:write a string to the file */#include <stdio.h> #include <string.h> #include <std lib.h> #define MAX 128intmain () {FILE *FP = NULL; Notice char *filepath = "Data/test.dat"; Char stringdes[] = "Hello World"; Stringdes[strlen (stringdes)] = ' n '; Char buf[max];/* open a file:file *fopen (const char *path, const char *mode); */#if 1 fp = fopen (FilePath, "at+"); if (NULL = = fp) {perror ("FP"); return-1; } printf ("File Open success! \ n "); #endif/* Write data block to a file:size_t fwrite (const void* buffer, size_t size, size_t count, file* Strea m); */int i; for (i = 0; I <= 2; i++) {fwrite (Stringdes,strlen (Stringdes), 1, FP); Fwrite ("\ n", 1, 1, FP); Fflush (FP); } printf ("File set start \ n"); Fseek (Fp,0,seek_set); Set start File Fread (Buf,strlen (stringdes), 1,FP); Buf[strlen (stringdes)] = ' n '; printf ("buf =%s \ n", buf); Fclose (FP);}
the contents of the Test.dat are as follows:
[email protected]:~/openandwritefile/zywtest/data# vim Test.dat
Hello World, Hello World,
Hello world
~
~
~
Linux opens a file and writes a string, reading the corresponding file at the same time--fopen ()/fwrite ()/fread ()