C language text file reading, writing and positioning (detailed introduction)

Table of contents

Introduction to text files

1. Open the file

2. File reading

 (1) fgetc function

(2) fgets function

(3) fscanf function

(4) fread function

3. Close the file

fclose(FILE *stream );

4. File writing

(1) fpuc function

(2) fputs function

(3) fprintf function

(4) fwrite function

5. Pointer positioning of text files

(1) rewind function

 (2) fseek function


        Sometimes we want to operate external files through programming languages, read and modify external files, or create files to achieve the desired purpose. In this regard, I use this article to introduce how to manipulate text files through C language.

       

Introduction to text files

A text file is a computer file, which is a typical sequential file, and its logical structure belongs to a streaming file. In particular, a text file refers to a file stored in an ASCII code mode (also called a text mode). More precisely, characters such as English and numbers are stored in ASCII codes, while Chinese characters are stored in machine codes. In addition to storing effective character information of the file (including information such as carriage return and line feed that can be represented by ASCII characters), the text file cannot store any other information.

Common formats for text files:

(1) .txt is a plain text document, which does not carry the color, type, and related modification format of the font.

(2) .doc is a formatted file created by Microsoft Word, which is generally used for graphic typesetting.

(3) .pdf has good encryption and is generally used in corporate offices.

(4) .doc and .docx The .doc file is the old version of the World document file format, and the .docx is the new version format.

(5).ASCLL refers to data and text files containing characters encoded in the standard ASCII character set .

Usually we can open Notepad or document to directly write content, and then save it, which successfully creates a text file, so how to create and write content through C language? The following is an introduction to the relevant text functions.

Standard header file : #include<stdio.h>

Here my file relative path is text.txt

1. Open the file

function:

FILE *fopen(char *filename, *type);

This function returns a pointer type. If the text is read successfully, it returns the address of the text, and if it fails to read, it returns a NULL pointer.

*type indicates the operation code, for example, r indicates the reading of the file, and w indicates the writing of the file

 

Example:

FILE *fp;

fp=fopen("text.txt","r");//表示对文件的读取

2. File reading

Read operation: fopen("text.txt","r");

 (1) fgetc function

Prototype: int fgetc( FILE *stream );

Return value: If the reading is successful, it will return a read character (similar to getchar), until the reading is completed and return EOF (Ask code value is -1) to indicate the end. Each time a character is read, after the reading is completed, the file pointer moves backward one position.

 Examples are as follows:

I know the contents of my file

#include<stdio.h>
#include<stdlib.h>//exit()函数的头文件
int main()
{
	FILE* fp;
	fp = fopen("text.txt", "r");
	if (feof(fp))
	{
		printf("NULL");
		exit(0);//表示如果读取为空文件就正常退出
	}
	char a;
	a = fgetc(fp);
	printf("%c", a);//在控制台输出读取的字符
}

 The fgetc function reads one character at a time. After the reading is completed, the file pointer moves back one position, and the next reading is the second character. For this, we can read all the contents of the file through a loop. For example:

	char a;
	for(; (a = fgetc(fp))!=EOF;)
	printf("%c", a);

(2) fgets function

原型:char *fgets( char *str, int numChars, FILE *stream );

Parameters: str represents the address of the string, numChars represents the maximum number of characters to be read, and stream represents the address of the file

Return value: Pass the characters of the file to the address of the string str, and then return the address of str.

#include<stdio.h>
#include<stdlib.h>//exit()函数的头文件
int main()
{
	FILE* fp;
	fp = fopen("text.txt", "r");
	if (feof(fp))
	{
		printf("NULL");
		exit(0);//表示如果读取为空文件就正常退出
	}
	char s[100];
	fgets(s, 10, fp);//最大读取10个
	printf("%s", s);
}

(3) fscanf function

 原型:int fscanf( FILE *stream, const char *format , argument ... );

Parameters: steam is the address of the file, format is the parameter that indicates the output, and argument is the content that indicates the output.

Return value: Returns the number of fields including the read conversion and allocation, if the read error or the end of the file is read, EOF is returned.

 Read the output string:

char s[100];
	fscanf(fp, "%s", s);//将读取的内容导入字符串s的地址
	printf("%s", s);

Read to output a single character: 

char a;
	fscanf(fp, "%c", &a);//读取单个字符导入a的地址
	printf("%c", a);

 Read the output integer:

	int b;
	fscanf(fp, "%d", &b);
	printf("%d", b);

fscanf is a more general function that can output a single character, multiple characters, shaping, etc.

(4) fread function

原型:size_t fread( void *buffer, size_t size, size_t count, FILE *stream );

Parameters: buffer indicates the address of the type to be read, size_t size indicates the number of bytes required for reading, size_t count indicates the number of reads, and stream indicates the address of the text file

Return Value: fread Returns the number of complete items read by the function, which may be less than  count if an error occurred, or  countthe end of the file was encountered before being reached.

#include<stdio.h>
#include<stdlib.h>//exit()函数的头文件
int main()
{
	FILE* fp;

	fp = fopen("text.txt", "r");
	if (feof(fp))
	{
		printf("NULL");
		exit(0);//表示如果读取为空文件就正常退出
	}
//魔鬼细节:使用fread函数读取有限个字符要对字符串进行初始化,也就是给字符串加上终止符
	char a[7] = { 0 };//实际上我要读取6个字符,但是我初始化要7个,最后一个是表示终止符
		fread(a, sizeof(char), 6, fp);
		printf("%s", a);
}
	char a[7] ;
	memset(a, 0, sizeof(a));//我们还可以通过memset 函数来进行初始化,其头文件是#include<string.h>
		fread(a, 1, 6, fp);
		printf("%s", a);

 The fread function is a very flexible function, we can use it to customize the number of characters to read from the file, and so on.

3. Close the file

fclose(FILE *stream );

stream is the text file address

fclose(fp);//fp是文本地址 FILE *fp

4. File writing

Write operation: fopen("text.txt","w");

Note: Close the file after writing, otherwise the file content may be lost.

(1) fpuc function

 Prototype: int fputc( int c, FILE *stream );

Parameters: c indicates the character to be written, and stream indicates the file address.

Return value: The return value is a character written. When EOF is returned, it means an error and the writing ends.

Note: After writing the content, the previous content will be destroyed.

#include<stdio.h>
#include<stdlib.h>//exit()函数的头文件
int main()
{
	FILE* fp;

	fp = fopen("text.txt", "w");
	if (feof(fp))
	{
		printf("NULL");
		exit(0);//表示如果读取为空文件就正常退出
	}
	fputc('s', fp);//写入一个字符s
fclose(fp);
}

At this point, you will find that there is nothing displayed in the console of the running result, we can open the text file to view the result

//类似于fgetc函数,我们也可以用循环来写入多字字符
char ch[10];
	scanf("%s", ch);
	for (int i = 0; ch[i]!='\0'; i++)
		fputc(ch[i], fp);

(2) fputs function

Prototype: int fputs( const char *str, FILE *stream );

Parameters: str means string, stream means file address

Return Value: If each function succeeds, it returns a non-negative value, the string written. When an error occurs, fputs  it will return EOF。

 Example:

fputs("china", fp);
//或者
char s[10];
scanf("%s,s);
fputs(s, fp);

(3) fprintf function

 原型:int fprintf( FILE *stream, const char *format , argument ... );

Parameters: steam is the address of the file, format is the parameter that indicates the output, and argument is the content that indicates the output.

Return value: fprintf return the number of bytes written, if the input is wrong, return EOF to indicate the end of the input.

for(int i=0;i<10;i++)
	fprintf(fp, "%d", i);//写入0~9
//字符串写入
char ch[20];
	scanf("%s", ch);
	fprintf(fp, "%s", ch);

(4) fwrite function

 原型:size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

Parameters: buffer indicates the address of the type to be read, size_t size indicates the number of bytes required for reading, size_t count indicates the number of reads, and stream indicates the address of the text file.

Return Value: fwrite Returns the complete number of items written by the function, which may be less than  count if an error occurred.

#include<stdio.h>
#include<stdlib.h>//exit()函数的头文件
int main()
{
	FILE* fp;

	fp = fopen("text.txt", "w");
	if (feof(fp))
	{
		printf("NULL");
		exit(0);//表示如果读取为空文件就正常退出
	}
	int a[10];
	for (int i = 0; i < 10; i++)//写入10个数字的数组
		scanf("%d", &a[i]);
	for (int i = 0; i < 10; i++)
		fwrite(&a[i],sizeof(int),1,fp);
}

 Don't be surprised, the result of writing is not a number, because the content written by fwrite will be converted into Asker code characters, and the random number should be displayed in the file as characters, not numbers, so these unrecognizable symbols will appear.

5. Pointer positioning of text files

(1) rewind function

Prototype: void rewind(FILE *stream)

Parameters: stream is the file address.

Function: Return the pointer of the text file to the beginning of the text.

 Example:

 (2) fseek function

原型:int fseek( FILE *stream, long offset, int origin );

Parameters: stream text address, offset indicates the number of bytes to move (a positive number indicates that the pointer moves to the right, and a negative number indicates that the pointer moves to the left), origin indicates the initial position.

Function: We can initialize the position of the pointer through the fseek function, and then read or write.

 The value of the origin initial position is as follows, and its corresponding function

 Example: How to read the string in the last line?

Contents of known files:

#include<stdio.h>
#include<stdlib.h>//exit()函数的头文件
int main()
{
	FILE* fp;

	fp = fopen("text.txt", "r");
	if (feof(fp))
	{
		printf("NULL");
		exit(0);//表示如果读取为空文件就正常退出
	}
	char a='a';
	fseek(fp, -1, SEEK_END);//把文件指针移动到文本末尾
	for (;a!='\n';)
	{
		a = fgetc(fp);//依次读取
		fseek(fp, -sizeof(char), SEEK_CUR);//由于每次读取了一个字符,文件指针会往后移动一个位置,所以要-2,从而实现在原先的基础上往上移动一个位置
	}
	fseek(fp,2, SEEK_CUR);//最后一次移动是在'\n'上面两个(字节)位置,所以要在次基础上向后移动两个位置
	char s[200] = { 0 };
	fgets(s,200, fp);
	puts(s);
	fclose(fp);
}

The result is as follows:

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/128255059