/*** a.txt ***/ this is a word helloworld /*** file.c ***/ #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { FILE *p = fopen("./a.txt","r"); while(!feof(p)) { char buf[100] = {0}; fscanf(p,"%s",buf); printf("%s\n",buf); } fclose(p); return 0; }
fscanf () function, scanf uses the same. fscanf string is read from a file, scanf string is read from the keyboard. (Spaces encountered stops)
/*** a.txt ***/ 23 + 45 = 35 + 63 = 34 + 45 = /*** file1.txt ***/ #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int a,b; FILE *p = fopen("./a.txt","r"); while(!feof(p)) { char buf[100] = {0}; //fgets(buf,"%s",p); //fscanf(p,"%s",buf); fscanf(p,"%d + %d = ",&a,&b); printf("a = %d , b = %d\n",a,b); //printf("%s\n",buf); } fclose(p); return 0; } /*** fprintf.c ***/ #include<stdio.h> #include<string.h> int main() { FILE *p = fopen("./b.txt","w"); char buf[100] = "hello world"; fprintf(p,"%s",buf); fclose(p); return 0; }
fread () function and fwrite () functions: manipulating text files and binary files
fopen () function can only read text files
/ * ** fread.c ** * / #include <stdio.h> int main () { the FILE * P = the fopen ( " ./a.txt " , " RB " ); char buf [ 100 ] = { 0 }; fread (buf, the sizeof ( char ), . 1 , P); // The first parameter is the buffer, the second parameter is a read byte, the third // parameter indicates the number of bytes read fourth parameter file pointer indicates the printf ( " buf =% S \ n- " , buf); fclose (P); return 0 ; } /*** fread1.c ***/ #include<stdio.h> int main() { FILE *p = fopen("./a.txt","rb"); while(!feof(p)) { char buf[20] = {0}; fread(buf,sizeof(char),sizeof(buf),p); printf("buf = %s\n",buf); } fclose(p); return 0; }
fread () function returns a value, the return type size_t, unsigned int == "% u
/*** fread.c ***/ #include<stdio.h> int main() { FILE *p = fopen("./c.txt","rb"); char buf[1024] = {0}; size_t res = fread(buf,sizeof(char),sizeof(buf),p); printf("res = %u\n",res); /* while(!feof(p)) { char buf[20] = {0}; fread(buf,sizeof(char),sizeof(buf),p); printf("buf = %s\n",buf); } */ fclose(p); return 0; } /*** c.txt ***/ asd
Operating results: res = 4 (end of the file have a newline character '\ n'?);
size_t res = fread(buf,sizeof(int),sizeof(buf),p);
Run Results: res = 1;
The results read text files in the operating results and windos environment above procedure would be different.
/*** fwrite.c ***/ #include<stdio.h> int main() { FILE *p = fopen("./d.txt","wb"); char buf[1024] = {0}; buf[0] = 'a'; buf[1] = 'b'; buf[2] = 'c'; fwrite(buf,sizeof(char),sizeof(buf),p); fclose(p); return 0; }
Operating results: abc
File size is 1K (buf) size of the array, followed by the full file is 0.
/*** fwrite.c ***/ #include<stdio.h> int main() { FILE *p = fopen("./d.txt","w"); int a = 0x12345678; fwrite(&a,sizeof(char),4,p); fclose(p); return 0; }