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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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.

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

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

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.

How to define the call declaration format of c language function How to define the call declaration format of c language function Apr 04, 2025 am 06:03 AM

C language functions include definitions, calls and declarations. Function definition specifies function name, parameters and return type, function body implements functions; function calls execute functions and provide parameters; function declarations inform the compiler of function type. Value pass is used for parameter pass, pay attention to the return type, maintain a consistent code style, and handle errors in functions. Mastering this knowledge can help write elegant, robust C code.

Integers in C: a little history Integers in C: a little history Apr 04, 2025 am 06:09 AM

Integers are the most basic data type in programming and can be regarded as the cornerstone of programming. The job of a programmer is to give these numbers meanings. No matter how complex the software is, it ultimately comes down to integer operations, because the processor only understands integers. To represent negative numbers, we introduced two's complement; to represent decimal numbers, we created scientific notation, so there are floating-point numbers. But in the final analysis, everything is still inseparable from 0 and 1. A brief history of integers In C, int is almost the default type. Although the compiler may issue a warning, in many cases you can still write code like this: main(void){return0;} From a technical point of view, this is equivalent to the following code: intmain(void){return0;}

See all articles