search
HomeBackend DevelopmentC#.Net TutorialWhat are the file reading and writing operations in 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);

*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
The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function