File operation in C language (ultimately invincible and detailed!)

Table of contents

1. File structure

1. The structure of the file pointer

2. The structure of file read and write operations

Second, the basic operation of the file

 Open the operation in the file

1. How to open the file

2. File name or path name

3. Sequential reading and writing of file operations 

 1、fgetc

 2、fputc

3、fgets 

4、fputs

         Here is a supplement to stdin and its relatives stdout and stderr:

5、fread

 6、fwrite

4. Random reading and writing of file operations

1、fseek

 2、ftell

 3、rewind


1. File structure

1. The structure of the file pointer

struct _iobuf { 
       char *_ptr; 
       int   _cnt; 
       char *_base; 
       int   _flag; 
       int   _file; 
       int   _charbuf; 
       int   _bufsiz; 
       char *_tmpfname; 
      }; 
typedef struct _iobuf FILE;

        The contents of the FILE type of different C compilers are not exactly the same, but they are similar.

2. The structure of file read and write operations

        The file operation we are talking about is carried out around this structure. Generally speaking, the variables of this FILE structure can be maintained through a FILE pointer, which is more convenient to use. Right now:

 FILE* pf;//文件指针变量

The approximate operation read and write operations are as follows:

        It can be seen that the file pointer is used to find the file information area. When we intend to read and write a file, the operations we perform: 1. Open the file. 2. The opened file maintains a file information area. And there are many different files in the information area, so our pointer can also access these files through some methods, see the second point for details. For example: there is a data.txt file, as follows:

                   


Second, the basic operation of the file

        Files should be opened before reading and writing, and should be closed after use.

        When writing a program, when opening a file, a FILE* pointer variable will be returned to point to the file, which is equivalent to establishing the relationship between the pointer and the file.

        ANSIC stipulates that the fopen function is used to open the file, and the fclose function is used to close the file

//打开文件 
FILE * fopen ( const char * filename, const char * mode ); 
//关闭文件 
int fclose ( FILE * stream );

 Example:

/* fopen fclose example */ 
#include <stdio.h> 
int main () 
{ 
 FILE * pFile; 
 //打开文件 
 pFile = fopen ("myfile.txt","w"); 
 //文件操作 
 if (pFile!=NULL) 
{ 
   fputs ("fopen example",pFile); //此操作为将文本行(即fopen example)输出到文件中
   //关闭文件 
   fclose (pFile); 
pFile=NULL;
} 
 return 0; 
} 

        In this regard, we can divide the file operation into three major blocks: 1. Open the file. 2. Operate on files. 3. Close the file.

Two of them are basically fixed, which are "open file" and "close file" operations.

        We can refer to the following formula to write:

//打开文件
FILE * pf;
pf = fopen(“文件名或者文件路径”,“文件打开方式”);
if(pf==NULL)
{
perror(“fopen”);
return;
}
//->文件操作

//<-

//封闭文件
fclose(pf);
pf=NULL;

        We only need to modify the file operations in it!


 Open the operation in the file

1. How to open the file

Open a file for writing only:

pFile = fopen ("myfile.txt","w"); 
//这里不管有无myfile.txt都可建立,如果有则对立面的数据进行操作,无则建立一个新的文件。
//ps:可以指定路径,此为默认。

 Open a read-only file:

pFile = fopen ("myfile.txt","r")//这里如果myfile.txt未建立过则会出错。这里我们可以在相应的路径下直接创建相应关键字的文件来解决这个问题。

2. File name or path name

For example, I want to open the contact.dat file in this path

I can do it like this  pFile = fopen (" contact.dat ", "Open file with");

You can also operate like this pFile = fopen (" E:\\gitee-related software\\practice_c\\txulu ", "file opening method");// The extra \ here is to cancel the effect of transfer

In this regard, we call the path of " contact.dat " to open the file as a relative path -> that is, it is under the current program path.

" E:\\gitee-related software\\practice_c\\txulu " is an absolute path -> this file can be in any location.

We also have extensions for relative paths:

If we want to create a file under the previous path, we can use . This to modify. It is called the current directory, and the upper directory is .. If we want to put the above contact.dat file into the x64 file, we can do this: ". \\x64\\ contact.dat ", if placed in the x64 of the upper directory: "..\\x64\\ contact.dat "

        Ok! Y(^o^)Y Knowing so many basic operations, then let's get to the point! Real coherent implementation of file operations!


3. Sequential reading and writing of file operations 

        Commonly used operations

        Seeing this, someone will ask what is the input and output stream? This stream is actually a channel for transmitting data. It can transfer data from other places, such as memory, files, etc. to the program or transfer the data in the program to other places.

        Here is a supplement to the input and output:

        A picture can understand:

 1、fgetc

        What it does is get characters from the stream.

原型:int fgetc ( FILE * stream );
/* fgetc example: money counter */
#include <stdio.h>
int main()
{
    FILE* pFile;
    int c;
    int n = 0;
    pFile = fopen("myfile.txt", "r");
    if (pFile == NULL) 
        perror("Error opening file");
    else
    {
        do {
            c = fgetc(pFile);
            if (c == '$') n++;
        } while (c != EOF);
        fclose(pFile);
        pFile = NULL;
        printf("The file contains %d dollar sign characters ($).\n", n);
    }
    return 0;
}

 2、fputc

        What it does is write characters to the stream.

原型:int fputc ( int character, FILE * stream );
#include <stdio.h>

int main()
{
    FILE* pFile;
    char c;

    pFile = fopen("alphabet.txt", "w");
    if (pFile != NULL) {

        for (c = 'A'; c <= 'Z'; c++)
            fputc(c, pFile);

        fclose(pFile);
        pFile = NULL;
    }
    return 0;
}

3、fgets 

        What it does is get a string from the stream.

        When the fgets function successfully reads a row of data, it returns a pointer to str. It returns a null pointer if end-of-file is reached or an error occurs. Note: The fgets function will also store the read newline character '\n' into the character array. If a line of data in the file exceeds the specified n characters, fgets will truncate this line of data and add a '\0' character after the last character.

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

//其中,str是一个字符数组,用来存储读取到的一行数据;num是一个整数,表示最多读取的字符数,
//包括字符串结尾的'\0';stream是一个文件指针,用来指定从哪个文件中读取数据。

/* fgets example */
#include <stdio.h>

int main()
{
    FILE* pFile;
    char mystring[100];

    pFile = fopen("myfile.txt", "r");
    if (pFile == NULL) perror("Error opening file");
    else {
        if (fgets(mystring, 100, pFile) != NULL)
            puts(mystring);
        fclose(pFile);
        pFile=NULL;    
    }
    return 0;
}

4、fputs

         What it does is write a string to the stream.

原型:int fputs ( const char * str, FILE * stream );
/* fputs example */
#include <stdio.h>
#include<stdlib.h>
int main()
{
	FILE* pFile;
	char sentence[256];
	printf("Enter sentence to append: ");
	fgets(sentence, 256, stdin);//stdin是啥?别急往下滑,下面有补充!
	pFile = fopen("mylog.txt", "a");
	fputs(sentence, pFile);
	fclose(pFile);
	pFile = NULL;
	return 0;
}

         Here is a supplement to stdin and its relatives stdout and stderr:

A picture:

stdin: Output information entered on the keyboard to a file or other places

stdout: output information from files or elsewhere to the screen

stderr: output error messages to the screen

5、fread

        What it does is read chunks of data from the stream.

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

//其中,ptr是指向要写入数据的指针,size是每个数据块的字节数,count是要写入的数据块的数量,
//stream是指向FILE结构体的指针,表示要写入的文件

#include<stdio.h>
struct S
{
	int a;
	float s;
	char str[10];
};

int main()
{
	struct S s = { 0 };

	FILE* pf = fopen("data.txt", "wb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//读文件
	fread(&s, sizeof(struct S), 1, pf);
	printf("%d %f %s\n", s.a, s.s, s.str);

	fclose(pf);
	pf = NULL;

	return 0;
}

 

 6、fwrite

        Its role is to write chunks of data to be streamed

原型:size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
//ptr为要写入的数据的指针,size为每个数据项的大小,count为要写入的数据项的个数,
//stream为文件指针。

#include<stdio.h>
struct S
{
	int a;
	float s;
	char str[10];
};

int main()
{
	struct S s = { 99, 6.18f, "bit" };

	FILE* pf = fopen("data.txt", "wb");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}
	//写文件
	fwrite(&s, sizeof(struct S), 1, pf);

	fclose(pf);
	pf = NULL;

	return 0;
}


4. Random reading and writing of file operations

1、fseek

        Its role is to locate the file pointer based on the position and offset of the file pointer.

                                      

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

/* fseek example */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  pFile = fopen ( "example.txt" , "wb" );
  fputs ( "This is an apple." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( " sam" , pFile );
  fclose ( pFile );
  return 0;
}
//这里将原来为This is an apple.从开头数第10位后变成了 sam

 2、ftell

        What it does is return the offset of the file pointer relative to the starting position.

原型:long int ftell ( FILE * stream );
/* ftell example : getting size of a file */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  long size;
  pFile = fopen ("myfile.txt","rb");
  if (pFile==NULL) perror ("Error opening file");
  else
 {
    fseek (pFile, 0, SEEK_END);   // 这里是从末尾开始
    size=ftell (pFile);
    fclose (pFile);
    pFile=NULL;
    printf ("Size of myfile.txt: %ld bytes.\n",size);//myfile.txt文件中的内容为$$因此可知为2
 }
  return 0;
}

 3、rewind

         Its function is to return the position of the file pointer to the beginning of the file.

原型:void rewind ( FILE * stream );
/* rewind example */
#include <stdio.h>
#include<stdlib.h>
int main()
{
	int n;
	FILE* pFile;
	char buffer[27];
	pFile = fopen("myfile.txt", "w+");
	for (n = 'A'; n <= 'Z'; n++)
		fputc(n, pFile);//一个一个将26个大写字母写入
	rewind(pFile);//将指针返回首部
	fread(buffer, 1, 26, pFile);//读出数据
	fclose(pFile);
	pFile = NULL;
	buffer[26] = '\0';
	puts(buffer);
	return 0;
}


        Thank you for your patience to see here ღ( ´・ᴗ・` ) to compare your heart, if there is any mistake, please kick the author o(╥﹏╥)o!

Guess you like

Origin blog.csdn.net/weixin_64038246/article/details/131765244