Home Backend Development C#.Net Tutorial What are the file reading and writing operations in C language?

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

Jul 27, 2020 pm 01:44 PM
c language

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

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

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

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

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

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

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

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

相关学习推荐: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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

How to output a countdown in C language How to output a countdown in C language Apr 04, 2025 am 08:54 AM

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

The concept of c language functions and their definition format The concept of c language functions and their definition format Apr 03, 2025 pm 11:33 PM

C language functions are reusable code blocks, receive parameters for processing, and return results. It is similar to the Swiss Army Knife, powerful and requires careful use. Functions include elements such as defining formats, parameters, return values, and function bodies. Advanced usage includes function pointers, recursive functions, and callback functions. Common errors are type mismatch and forgetting to declare prototypes. Debugging skills include printing variables and using a debugger. Performance optimization uses inline functions. Function design should follow the principle of single responsibility. Proficiency in C language functions can significantly improve programming efficiency and code quality.

What are the types of return values ​​of c language function? Summary of types of return values ​​of c language function? What are the types of return values ​​of c language function? Summary of types of return values ​​of c language function? Apr 03, 2025 pm 11:18 PM

The return value types of C language function include int, float, double, char, void and pointer types. int is used to return integers, float and double are used to return floats, and char returns characters. void means that the function does not return any value. The pointer type returns the memory address, be careful to avoid memory leakage.结构体或联合体可返回多个相关数据。

CS-Week 3 CS-Week 3 Apr 04, 2025 am 06:06 AM

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

See all articles