Home  >  Article  >  Backend Development  >  What are the file reading and writing operations in C language?

What are the file reading and writing operations in C language?

coldplay.xixi
coldplay.xixiOriginal
2020-07-27 13:44:174113browse

C language file reading and writing operations include: 1. The function to read and write characters in the file, the code is [int fgetc(FILE *stream)]; 2. The function to read and write strings in the file, the code is [ int fputs(char *string,FILE *stream)].

What are the file reading and writing operations in C language?

C language file read and write operations include:

1. File opening function fopen()

The file opening operation means that the file specified by the user will be allocated a FILE structure area in the memory, and the pointer of the structure will be returned to the user program. In the future, the user program can use this FILE pointer to implement Specified file access operation. When using the open function, the file name and file operation mode (read, write or read-write) must be given.

If the file name does not exist, it means creating it (only for writing files, for An error occurs when reading the file) and points the file pointer to the beginning of the file. If a file with the same name already exists, delete the file. If there is no file with the same name, create the file and point the file pointer to the beginning of the file.

fopen(char *filename,char *type);

*filename is the file name pointer of the file to be opened, which is generally expressed as a file name enclosed in double quotes, or a path name separated by double backslashes. The *type parameter indicates the operation method for opening the file. The available operation methods are as follows:

  • Meaning "r" opens, read-only;

  • "w" opens, the file pointer points to the beginning. , write only;

  • "a" opens, points to the end of the file, appends to the existing file;

  • "rb" opens a binary File, read-only;

  • "wb" opens a binary file, write-only;

  • "ab" opens a binary file, appends ;

  • "r " Open an existing file in read/write mode;

  • "w " Create an existing file in read/write mode New text file;

  • "a " Open a file for appending in read/write mode;

  • "rb " Open it in read/write mode Open a binary file in write mode;

  • "wb " Create a new binary file in read/write mode;

  • "ab " Open a binary file in read/write mode for appending;

When fopen() is used to successfully open a file, this function will return a FILE pointer. If the file fails to be opened, it will be returned A NULL pointer.

2. Close the file function fclose()

After the file operation is completed, you must use the fclose() function to close it. This is because the open file needs to be written. At the time of writing, if the space in the file buffer is not filled by written content, the content will not be written to the open file and will be lost. Only when the open file is closed, the content remaining in the file buffer can be written to the file, thereby making the file complete.

Furthermore, once the file is closed, the FILE structure corresponding to the file will be released, so that the closed file is protected, because access operations to the file will not be performed at this time. Closing a file also means releasing the file's buffer.

int fclose(FILE *stream);

It means that this function will close the file corresponding to the FILE pointer and return an integer value. If the file was successfully closed, a 0 value is returned, otherwise a non-zero value is returned.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
    FILE *fp;   //  头文件#include <stdio.h>
    if((fp=fopen("123.txt","w"))==NULL)
    {
        printf("file cannot open \n");
        //exit(0);  头文件#include <stdlib.h>
        //exit结束程序,一般0为正常推出,其它数字为异常,其对应的错误可以自己指定。
    }
    else
        printf("file opened for writing \n");
    if(fclose(fp)!=0)
        printf("file cannot be closed \n");
    else
        printf("file is now closed \n");
    return 0;
}

3. Reading and writing files

(1). Function to read and write characters in a file (only read and write one character in the file at a time):

int fgetc(FILE *stream);
int getchar(void);
int fputc(int ch,FILE *stream);
int putchar(int ch);
int getc(FILE *stream);
int putc(int ch,FILE *stream);

fgetc()The function will read a character from the file pointed to by the stream pointer, for example: ch=fgetc(fp); will read a character from the file pointed by the stream pointer fp The character is read and assigned to ch. When the fgetc() function is executed, if the file pointer points to the end of the file, the end-of-file flag EOF is encountered (its corresponding value is -1), and the function returns -1 to ch. , it is commonly used in programs to check whether the return value of this function is -1 to determine whether the end of the file has been reached, thereby deciding whether to continue.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
    FILE *fp;
    char ch;
    if((fp=fopen("123.txt","r"))==NULL)
        printf("file cannot open \n");
    else
        printf("file opened for writing \n");
    while((ch=fgetc(fp))!=EOF)
        fputc(ch,stdout); //这里是输出到屏幕
    if(fclose(fp)!=0)
        printf("file cannot be closed \n");
    else
        printf("file is now closed \n");
    return 0;
}

This program opens the 123.txt file in read-only mode. When executing the while loop, the file pointer moves back one character position each time it loops. Use the fgetc() function to read the character specified by the file pointer into the ch variable, and then use the fputc() function to display it on the screen. When the end-of-file mark EOF is read, the file is closed. The above program uses the fputc() function, which writes the value of the character variable ch to the file specified by the stream pointer. Since the stream pointer uses the FILE pointer stdout of the standard output (display), the read characters will displayed on the monitor. Another example: fputc(ch,fp); This function executes the structure and sends the character represented by ch to the file pointed to by the stream pointer fp.

In TC, putc() is equivalent to fputc(), and getc() is equivalent to fgetc(). putchar(c) is equivalent to fputc(c,stdout); getchar() is equivalent to fgetc(stdin). Note that the use of char ch here is actually unscientific, because when the end mark is finally judged, ch!=EOF is looked at, and the value of EOF is -1, which is obviously incomparable with char. Therefore, for some uses, we define it as int ch.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
    FILE *fp;
    if((fp=fopen("123.txt","a"))==NULL)
        printf("file cannot open \n");
    else
        printf("file opened for writing \n");
    char ch=&#39;e&#39;;
    fputc(ch,fp); //输入到文件中
    if(fclose(fp)!=0)
        printf("file cannot be closed \n");
    else
        printf("file is now closed \n");
    return 0;
}

(2). Functions for reading and writing strings in files

char *fgets(char *string,int n,FILE *stream);
char *gets(char *s);
int fprintf(FILE *stream,char *format,variable-list);
int fputs(char *string,FILE *stream);
char *puts(char *s);
int fscanf(FILE *stream,char *format,variable-list);

其中fgets()函数将把由流指针指定的文件中n-1个字符,读到由指针string指向的字符数组中去,例如: fgets(buffer,9,fp); 将把fp指向的文件中的8个字符读到buffer内存区,buffer可以是定义的字符数组,也可以是动态分配的内存区。 

注意,fgets()函数读到'/n'就停止,而不管是否达到数目要求。同时在读取字符串的最后加上'/0'。 fgets()函数执行完以后,返回一个指向该串的指针。如果读到文件尾或出错,则均返回一个空指针NULL,所以长用feof()函数来测定是否到了文件尾或者是ferror()函数来测试是否出错,

检测是否已到文件尾,是返回真,否则返回0,其原型是int feof(FILE *stream);

例:if(feof(fp))printf("已到文件尾");

原型是int ferror(FILE *stream);返回流最近的错误代码,可用clearerr()来清除它,clearerr()的原型是void clearerr(FILE *stream);

例:printf("%d",ferror(fp));

例如下面的程序用fgets()函数读test.txt文件中的第一行并显示出来:

#include "stdio.h" 
int main() {
    FILE *fp; 
    char str[128]; 
    if((fp=fopen("123.txt","r"))==NULL) {
        printf("cannot open file/n"); exit(1);
    } 
    while(!feof(fp)) {
        if(fgets(str,128,fp)!=NULL)
        printf("%s",str);
    }
    fclose(fp);
}

相关学习推荐:C视频教程

The above is the detailed content of What are the file reading and writing operations in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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