In C language, file operations are completed by library functions.
Recommendation: "c Language Tutorial"
To read a txt file, first use the file opening function fopen().
The fopen function is used to open a file. The general form of its call is: file pointer name = fopen (file name, using file mode). Among them, the "file pointer name" must be a pointer specified as a FILE type. Variable, "filename" is the file name of the opened file. "Use file method" refers to the type of file and operation requirements. "filename" is a string constant or an array of strings.
Secondly, use the file read and write functions to read the file.
Provides a variety of file reading and writing functions in C language:
·Character reading and writing functions: fgetc and fputc
·String reading and writing functions: fgets and fputs
·Data block read and write functions: freed and fwrite
·Format read and write functions: fscanf and fprinf
Finally, use file close at the end of file reading The function fclose() closes the file.
Example:
#include <stdio.h> #include <stdlib.h> #include <assert.h> typedef struct student{ char name[32]; int no; char sex[16]; float score; } stu; int main(int argc, char* argv[]) { //打开文件 FILE * r=fopen("A.txt","r"); assert(r!=NULL); FILE * w=fopen("B.txt","w"); assert(w!=NULL); //读写文件 stu a[128]; int i=0; while(fscanf(r,"%s%d%s%f",a[i].name,&a[i].no,a[i].sex,&a[i].score)!=EOF) { printf("%s\t%d\t%s\t%g\n",a[i].name,a[i].no,a[i].sex,a[i].score);//输出到显示器屏幕 fprintf(w,"%s\t%d\t%s\t%g\n",a[i].name,a[i].no,a[i].sex,a[i].score);//输出到文件B.txt i++; } //关闭文件 fclose(r); fclose(w); system("pause"); return 0; }
The result after compilation and running is as follows:
##For more programming related content, please pay attention to php Chinese websiteprogramming introduction column!
The above is the detailed content of How to read the content of txt file in c language?. For more information, please follow other related articles on the PHP Chinese website!