How to read the content of txt file in c language?

Release: 2020-03-09 08:48:08
Original
27760 people have browsed it

How to read the content of txt file in c language?

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;
}
Copy after login

The result after compilation and running is as follows:

How to read the content of txt file in c language?

##For more programming related content, please pay attention to php Chinese website

programming 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!