Linux opens a file and writes a string that reads the corresponding file information
in Linux, using the C language, use the fopen () function to open a file (if no file exists, create a new one, such as Data/test.dat),
and use the
fwrite () writes the appropriate string to it, each time the input writes are wrapped, and finally the corresponding information is read with Fread ().
the corresponding code is as follows: 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 Test.dat are as follows:
[email protected]:~/openandwritefile/zywtest/data# vim Test.dat
Hello World, Hello World,
Hello world
~ , &NB Sp , &NB Sp
~ , &N Bsp , &NB Sp
~
Linux opens a file and writes a string, reading the corresponding file information--fopen ()/fwrite ()/fread ()