C language file operation related functions

Keywords: C C++

Header file: stdio.h

#include <stdio.h> 

File open close function

File open (fopen)

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

FILE * fopen(const char * filename, const char * mode);
  • Function: open file
  • Parameters:
    filename: the name of the file to be opened, plus the path as needed
    mode: permission settings for opening files
  • Return value:
    Success: file pointer
    Failed: NULL

Optional value of parameter mode

modemeaning
"r"Open, read-only, file must already exist.
"w"Write only. If the file does not exist, it will be created. If the file already exists, the file length will be truncated to 0 bytes. Re write, that is, replace the original file content, and the file pointer points to the end.
"a"Data can only be appended at the end of the file. If the file does not exist, it will be created
"rb"Open a binary file, read-only
"wb"Open a binary file and write only
"ab"Open a binary file and append
"r+"Read and write are allowed. The file must already exist
"w+"Read and write are allowed. If the file does not exist, it will be created. If the file already exists, the file length will be truncated to 0 bytes and then written again.
"a+"Allow reading and appending data, and create if the file does not exist
"rb+"Open a binary file in read / write mode
"wb+"Create a new binary file in read / write mode
"ab+"Open a binary file for append in read / write mode

case

Check the return value of fopen:
If the function fails, it returns a NULL value. If the program does not check for errors, the NULL pointer is passed to subsequent I/O functions. They will perform indirect access to this pointer and will fail

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void test() {

	FILE *fp = NULL;

	// The path form of "\ \" can only be used in windows
	// The path form of "/" is available on both windows and linux platforms. It is recommended to use this path form
	// The path can be relative or absolute
	fp = fopen("../test", "w");
	//fp = fopen("..\\test", "w");

	if (fp == NULL) //If it returns null, it indicates that the opening failed
	{
		//perror() is a standard error printing function, which can print the error reason of calling library function
		perror("open");
		return;
	}
}

int main()
{
	test();
	return 0;
}

File close (fclose)

After the FILE operation is completed, if the program does not end, it must be closed with the fclose() function. This is because when writing to an open FILE, if the space in the FILE buffer is not filled with the written contents, these contents will not be written to the open FILE. Only when the open FILE is closed, the contents remaining in the FILE buffer can be written to the FILE, so as to make the FILE complete. Moreover, once the FILE is closed, the FILE structure corresponding to the FILE will be released, so that the closed FILE can be protected, because the access operation to the FILE will not be carried out at this time. Closing the FILE also means that the buffer of the FILE is released.

int fclose(FILE * stream);
  • Function: close files previously opened by fopen(). This action causes the data in the buffer to be written to the file and releases the file resources provided by the system.
  • Parameters:
    stream: file pointer
  • Return value:
    Success: 0
    Failed: - 1

It means that the function will close the FILE corresponding to the FILE pointer and return an integer value. If the FILE is successfully closed, a value of 0 is returned; otherwise, a value other than 0 is returned

File read / write related functions

Overview

Basic functions related to file reading and writing include the following aspects:

  • Read and write files according to characters: fgetc(), fputc()
  • Read and write files by line: fputs(), fgets()
  • Read and write files by block: fread(), fwirte()
  • Read and write files according to format: fprintf(), fscanf()
  • Read and write files according to random locations: fseek(), ftell(), rewind()

Character read / write function

int fputc(int ch, FILE * stream);
  • Function: convert ch to unsigned char and write it to the file specified by stream
  • Parameters:
    ch: the character that needs to be written to the file
    stream: file pointer
  • Return value:
    Success: the characters of the file were successfully written
    Failed: Return - 1
int fgetc(FILE * stream);
  • Function: read a character from the file specified by stream
  • Parameters:
    stream: file pointer
  • Return value:
    Success: returns the read characters
    Failed: - 1
int feof(FILE * stream);
  • Function: detect whether the end of the file is read
  • Parameters:
    stream: file pointer
  • Return value:
    Non 0 value: has reached the end of the file
    0: not to the end of the file

Character reading and writing case

A character in the file pointed to by the stream pointer fp will be read out and assigned to ch. when executing the fgetc() function, if the file pointer points to the end of the file, the end of file flag EOF (its corresponding value is - 1) will be encountered, and the function returns a - 1 to ch. in the program, it is often used to check whether the return value of the function is - 1 to judge whether the end of the file has been read, so as to decide whether to continue.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void test() {

	//Write file
	FILE* fp_write = NULL;
	//Open file in write mode
	fp_write = fopen("./mydata.txt", "w+");
	if (fp_write == NULL) {
		return;
	}

	char buf[] = "this is a test for pfutc!";
	for (int i = 0; i < strlen(buf); i++) {
		fputc(buf[i], fp_write);
	}

	fclose(fp_write);

	//read file
	FILE* fp_read = NULL;
	fp_read = fopen("./mydata.txt", "r");
	if (fp_read == NULL) {
		return;
	}

#if 1
	//Judge the end of the file. Note: output one more space
	while (!feof(fp_read)) {
		printf("%c", fgetc(fp_read));
	}
#else
	char ch;
	while ((ch = fgetc(fp_read)) != EOF) {
		printf("%c", ch);
	}
#endif
}

int main()
{
	test();
	return 0;
}

The output result is:

Row read / write function

int fputs(const char * str, FILE * stream);
  • Function: write the string specified by str to the file specified by stream, and the string terminator '\ 0' is not written to the file.
  • Parameters:
    str: String
    stream: file pointer
  • Return value:
    Success: 0
    Failed: - 1
char * fgets(char * str, int size, FILE * stream);
  • Function: read characters from the file specified by stream and save them to the memory space specified by str until a newline character appears, the end of the file is read, or the size - 1 character has been read. Finally, the character '\ 0' will be automatically added as the end of the string.
  • Parameters:
    str: String
    Size: Specifies the length of the maximum read string (size - 1)
    stream: file pointer
  • Return value:
    Success: String successfully read
    End of file read or error: NULL

Line read / write case

Write four lines to the file and read the output.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void test() {

	//Write file
	FILE* fp_write = NULL;
	//Open file in write mode
	fp_write = fopen("./mydata.txt", "w+");
	if (fp_write == NULL) {
		perror("fopen:");
		return;
	}

	char* buf[] = {
		"01 Qian this is a test for pfutc!\n",
		"02 Qian this is a test for pfutc!\n",
		"03 Qian this is a test for pfutc!\n",
		"04 Qian this is a test for pfutc!\n",
	};
	for (int i = 0; i < 4; i++) {
		fputs(buf[i], fp_write);
	}

	fclose(fp_write);

	//read file
	FILE* fp_read = NULL;
	fp_read = fopen("./mydata.txt", "r");
	if (fp_read == NULL) {
		perror("fopen:");
		return;
	}

	//Judge end of file
	while (!feof(fp_read)) {
		char temp[1024] = { 0 };
		fgets(temp, 1024, fp_read);
		printf("%s", temp);
	}

	fclose(fp_read);
}


int main()
{
	test();
	return 0;
}

The operation result is:

Block read / write function

size_t fwrite(
	const void *ptr, 
	size_t size, 
	size_t nmemb, 
	FILE *stream
);
  • Function: write content to the file in the form of data block
  • Parameters:
    ptr: address to write file data
    size: size_t is of type unsigned int, which specifies the block data size to be written to the file content
    Nmemb: the number of blocks written to the file. The total size of the written file data is: size * nmemb
    stream: pointer to the file that has been opened
  • Return value:
    Success: the number of blocks actually successfully written to the file data. This value is equal to nmemb
    Failed: 0
size_t fread(
	void *ptr, 
	size_t size, 
	size_t nmemb, 
	FILE *stream
);
  • Function: read contents from files in the form of data blocks
  • Parameters:
    ptr: memory space for storing read data
    size: size_t is of type unsigned int, which specifies the block data size for reading the contents of the file
    Nmemb: the number of read file blocks. The total size of read file data is: size * nmemb
    stream: pointer to the file that has been opened
  • Return value:
    Success: the number of blocks of content successfully read. If this value is smaller than nmemb but greater than 0, it indicates that the end of the file has been read.
    Failed: 0

Block read / write case

Establish a teacher structure, write teacher information, read information from the file, and output:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

// Teacher structure
typedef struct _TEACHER {
	char name[64];
	int age;
}Teacher;

void test() {
	//Write file
	FILE* fp_write = NULL;
	//Open file in write mode
	fp_write = fopen("./mydata.txt", "wb");
	if (fp_write == NULL) {
		perror("fopen:");
		return;
	}

	Teacher teachers[4] = {
		{ "Qian", 33 },
		{ "benefit", 28 },
		{ "Jos", 45},
		{ "Mimi", 35}
	};

	for (int i = 0; i < 4; i++) {
		fwrite(&teachers[i], sizeof(Teacher), 1, fp_write);
	}
	//Close file
	fclose(fp_write);

	//read file
	FILE* fp_read = NULL;
	fp_read = fopen("./mydata.txt", "rb");
	if (fp_read == NULL) {
		perror("fopen:");
		return;
	}

	Teacher temps[4];
	fread(&temps, sizeof(Teacher), 4, fp_read);
	printf("Output teachers' information:\n");
	for (int i = 0; i < 4; i++) {
		printf("full name:%s  Age:%d\n", temps[i].name, temps[i].age);
	}

	fclose(fp_read);
}


int main()
{
	test();
	return 0;
}

The operation result is:

fscanf fprintf

int fprintf(FILE * stream, const char * format, ...);
  • Function: convert and format data according to the parameter format string, and then output the result to the file specified by stream until the string terminator '\ 0' appears.
  • Parameters:
    stream: open file
    Format: string format. The usage is the same as printf()
  • Return value:
    Success: the number of characters actually written to the file
    Failed: - 1
int fscanf(FILE * stream, const char * format, ...);
  • Function: read the string from the file specified by stream, and convert and format the data according to the parameter format string.
  • Parameters:
    stream: open file
    Format: string format. The usage is the same as scanf()
  • Return value:
    Success: the number of characters actually read from the file
    Failed: - 1

Note: fscanf ends when it encounters spaces and line breaks.

Format read / write cases

Write a line of string with spaces and read the output:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void test() {

	//Write file
	FILE* fp_write = NULL;
	//Open file in write mode
	fp_write = fopen("./mydata.txt", "w");
	if (fp_write == NULL) {
		perror("fopen:");
		return;
	}

	fprintf(fp_write, "he llo wor ld :%d!", 99999);

	//Close file
	fclose(fp_write);

	//read file
	FILE* fp_read = NULL;
	fp_read = fopen("./mydata.txt", "rb");
	if (fp_read == NULL) {
		perror("fopen:");
		return;
	}

	char temps[1024] = { 0 };
	while (!feof(fp_read)) {
		fscanf(fp_read, "%s", temps);
		printf("%s", temps);
	}

	fclose(fp_read);
}

int main()
{
	test();
	return 0;
}

Random read-write function

Note: the random reading and writing here is not really random reading and writing at the random position of the system, but at the random position you want to specify

int fseek(FILE *stream, long offset, int whence);
  • Function: move the read / write position of file stream (file cursor).
  • Parameters:
    stream: pointer to the file that has been opened
    offset: the number of displacements (offsets) moved according to the when. It can be positive or negative. If it is positive, it moves to the right relative to the when. If it is negative, it moves to the left relative to the when. If the number of bytes moved forward exceeds the beginning of the file, an error is returned. If the number of bytes moved backward exceeds the end of the file, the file size will be increased when writing again.
    Where: its value is as follows:
    • SEEK_SET: move offset bytes from the beginning of the file
    • SEEK_CUR: move offset bytes from the current position
    • SEEK_END: moves offset bytes from the end of the file
  • Return value:
    Success: 0
    Failed: - 1
long ftell(FILE *stream);
  • Function: obtain the read and write position of file stream (file cursor).
  • Parameters:
    stream: pointer to the file that has been opened
  • Return value:
    Success: the read / write position of the current file stream (file cursor)
    Failed: - 1
void rewind(FILE *stream);
  • Function: move the read / write position of the file stream (file cursor) to the beginning of the file.
  • Parameters:
    stream: pointer to the file that has been opened
  • Return value:
    No return value

Random reading and writing cases

Read different teachers at random positions:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct _TEACHER {
	char name[64];
	int age;
}Teacher;

void test() {
	//Write file
	FILE* fp_write = NULL;
	//Open file in write mode
	fp_write = fopen("./mydata.txt", "wb");
	if (fp_write == NULL) {
		perror("fopen:");
		return;
	}

	Teacher teachers[4] = {
		{ "1 Qian", 33 },
		{ "2 benefit", 28 },
		{ "3Jos", 45},
		{ "4 Mimi", 35}
	};

	for (int i = 0; i < 4; i++) {
		fwrite(&teachers[i], sizeof(Teacher), 1, fp_write);
	}
	//Close file
	fclose(fp_write);

	//read file
	FILE* fp_read = NULL;
	fp_read = fopen("./mydata.txt", "rb");
	if (fp_read == NULL) {
		perror("fopen:");
		return;
	}

	Teacher temp;
	// Move from beginning of file: read third
	fseek(fp_read, sizeof(Teacher) * 2, SEEK_SET);
	fread(&temp, sizeof(Teacher), 1, fp_read);
	printf("Name:%s Age:%d\n", temp.name, temp.age);

	memset(&temp, 0, sizeof(Teacher));

	// Move from end of file: read fourth
	fseek(fp_read, -(int)sizeof(Teacher), SEEK_END);
	fread(&temp, sizeof(Teacher), 1, fp_read);
	printf("Name:%s Age:%d\n", temp.name, temp.age);

	// Reread from the beginning of the file
	rewind(fp_read);
	fread(&temp, sizeof(Teacher), 1, fp_read);
	printf("Name:%s Age:%d\n", temp.name, temp.age);

	fclose(fp_read);
}

int main()
{
	test();
	return 0;
}

The operation result is:

Comprehensive case of file operation

More content, please move to another blog: https://yangyongli.blog.csdn.net/article/details/121025022

Posted by parkie on Thu, 28 Oct 2021 11:37:42 -0700