当前位置:网站首页>[C language] C language file operation | C language file reading and writing | single character reading and writing | string reading and writing | format reading and writing | binary form reading and

[C language] C language file operation | C language file reading and writing | single character reading and writing | string reading and writing | format reading and writing | binary form reading and

2022-06-12 01:35:00 MuShan-bit

One What is a document

ps: Except folders , It's all documents

The suffix of the file : .docx .txt .c .cpp .exe .bat .csv …

Two file name

name . suffix

3、 ... and File path

1 Relative paths : From the current project to the target file

2 Absolute path : Start from the root directory to the target file

With : route + name . suffix To determine the file

Four Operation file ( Text begins )

For more information, please refer to :https://www.runoob.com/cprogramming/c-file-io.html

     1、 Define file pointer   FILE*file;
     2、open(“ route ”,“ Open mode ”) Open file 
     3、 How to open the file 
         “r”( read-only )  To enter data , Open an existing text file   error 
         “w”( Just write )  To output data , Open a text file   New file 
         “a”( Additional )  Add data to the end of the text file   error 
         “rb”( read-only )  To enter data , Open an existing binary file   error 
         “wb”( Just write )  To output data , Open a binary file   New file 
         “ab”( Additional )  Add data to the end of the binary file   error 
         “r+”( Reading and writing )  For reading and writing , Open a text file   error 
         “w+”( Reading and writing )  For reading and writing , Open a text file   New file 
         “a+”( Reading and writing )  For reading and writing , Open a text file   error 
         “rb+”( Reading and writing )  For reading and writing , Open a binary file   error 
         “wb+”( Reading and writing )  For reading and writing , Open a binary file   New file 
         “ab+”( Reading and writing )  For reading and writing , Open a binary file   error 
     4fclose() Close file 
     5、fgetc( The file pointer )  Read a character 
     6fputc( character , The file pointer )  Write a character 
     7、fgets( Character pointer , size , The file pointer )  Read one line of characters , read n individual 
     8fpust( character string , The file pointer )  Write a string of characters 
     9fprintf( The file pointer ," Format placeholder ...", Variable ...);   Format write file 
    10fscanf( The file pointer ,“ Format placeholder ...", Variable ...);  Format read 
 Read and write data in binary mode 
    11fread( The character array used to save , The size of the data type , Number of data , The file pointer ); Get the formatted... From the file 
 data 
    12fwrite( The character array needs to be written in ,  The size of the data type , Number of data ,  The file pointer ); Write data to file 
    13fseek( The file pointer , Offset , The starting point );   Move file pointer 
         The offset is a positive number and moves back , Negative numbers move forward 
         For starting point 012 Instead of 
            0SEEK_SET) Represents the starting position of the file 
            1SEEK_CUR) Represents the current location 
            2SEEK_END ) Represents the position at the end of the file 
    14ftell( The file pointer )   Get the offset of the file pointer 
    15feof( The file pointer )  Judge whether the file pointer reads to the end , Read to the end and return true , On the contrary, false 
              
 remarks : When doing file operations , Remember how to write the file and read it out , It's best not to read and write at the same time , Pay attention to your operation and play 
 The way of opening 

One Single character reading and writing

stay main.c ( Project source file ) In the same folder establish tese1.txt file

Type in the contents of the file : for example : “IAmMuShan”

* Chinese is not recommended here fgetc() Single character read / write read 1 byte , A Chinese character is generally 2 byte Can't read normally

My code is new , Quote here : https://bbs.csdn.net/topics/390325904

key word : fgetc( Get a single character ) putchar ( Release a single character )

void function1() {
    
	// 1  Defining variables :  The file pointer 
	FILE* pfile = NULL;
	char ch = 0;

	// 2  Open file ( The file pointer points to the file address ) fopen Parameters :  File path , Open mode 
	pfile = fopen("text1.txt", "r");   // r  As read-only   If the file here is not in the same path as the code source file, fill in the path 

	// 3  Read ( file  ==>  Program )
	//  Get a character  fgetc Parameters :  file 
	ch = fgetc(pfile);

	// 4  Output and read characters on the console 
	putchar(ch);
	printf("\nch = %c\n", ch);              //  result  : i

	// 5  Continue reading backwards 
	putchar(fgetc(pfile));
	printf("\n%c\n",fgetc(pfile));          //  result  : a
	// ==>  Just call the method   Will automatically read back 

	// 6  Close file ( Cancel the file pointer address pointing to )
	fclose(pfile);
	pfile = NULL;

	// 7  Reopen the file 
	pfile = fopen("text1.txt", "w");          // Open the file as a write ;

	// 8  Write a single character to a file ( Program  ==>  file )
	fputc('X',pfile);
	// ==>  Will clear the original data   To write 
	fputc('Y',pfile);
	// ==>  Write for the first time before closing   Will be automatically written in sequence 

	// 9  Close file 
	fclose(pfile);
	pfile = NULL;

}

Two Reading and writing of strings

stay main.c ( Project source file ) In the same folder establish tese2.txt file

Type in the contents of the file : for example : “ILoveYou”

* Although the theory here is that if you choose 4 A length will come out 2 Look like a Chinese character , It is still not recommended to use Chinese , Depending on the compiler , There may be all kinds of garbled code

key word : fgets( Get string ) fputs( Release string )

void function2() {
    
	FILE * pfile = NULL;
	char str[20] = {
     };             // Initialize string array 

	pfile = fopen("text2.txt","r"); // Open the file in read-only mode 

	//  String reading function ( file  ==>  Program )
	//  Parameters : Storage target , length (byte), Resource file 
	fgets(str , 5 , pfile);
	puts(str);
	printf("%s\n",str);
	// ==>  Only... Will appear here 4 Characters   because '\0' Take a place (\0 Flag for the end of the string )
	
	fclose(pfile);
    pfile = NULL;
    
	pfile = fopen("text2.txt", "a"); // a: Additional 
	
	char str1[10] = "hello";
	
	//  String output function ( Program ==> file )
	//  Parameters : resources , file 
	fputs(str1, pfile);
	
	fclose(pfile);
    pfile = NULL;
    
}

3、 ... and Format reading and writing

stay main.c ( Project source file ) In the same folder establish tese3.txt file

characteristic : Formatting Gu Mingsi means that the initial content will be cleared when reading and writing

key word : fscanf( Format input ) fprintf( Format output )

//  3、 ... and   Format reading and writing 
void function3()
{
    
	FILE* pfile;
	int num0 = 100, num1 = 0;
	float f0 = 1.2f, f1 = 0.0f;
	char str0[10] = "123abc#", str1[10] = {
    };

	pfile = fopen("text3.txt", "w");      // Here, if the file is not created or cannot be found, the file name will be automatically created in the path 

	//  Program ==> file 
	//  Parameters :  file , Format ,obj
	fprintf(pfile, "%d,%f,%s", num0, f0, str0);

	fclose(pfile);
	pfile = NULL;

	pfile = fopen("text3.txt", "r");      // Here, if the file is not created or the file name cannot be found   Then the computer is confused, hahaha 

	//  file ==> Program 
	fscanf(pfile, "%d,%f,%s", &num1, &f1, &str1);

	printf("%d , %f , %s\n", num1, f1, str1);       // result :100 , 1.200000 , 123abc#

	fclose(pfile);
	pfile = NULL;
    
}

Four Read and write in binary form

key word : fwrite( For binary writing ) fread( For binary reading )

//  Four   Read and write in binary form 
void function4()
{
    
	FILE* pfile = NULL;
	int arr0[10] = {
     0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int arr1[10] = {
    };

	pfile = fopen("text4.txt", "wb");         // "wb" Write... In binary form 
	fwrite(arr0, sizeof(int), 10, pfile);
	fclose(pfile);
	pfile = NULL;

	pfile = fopen("text4.txt", "rb");         // "rb" Read in binary form 
	fread(arr1, sizeof(int), 10, pfile);
	for (size_t i = 0; i < 10; i++)
	{
    
		printf("%d ", arr1[i]);               //  result : 0 1 2 3 4 5 6 7 8 9
	}
	fclose(pfile);
	pfile = NULL;

}

Because it is binary reading and writing text4.txt Unable to view content when opening

5、 ... and Read and write at the specified location

adopt fseek( Offset function ) Change the reading and writing position

key word : fseek_ Offset function

usage : fseek( The file pointer , Offset ( In bytes ), initial position )

Initial position preprocessing constant :

SEEK_CUR 1 The current position

SEEK_END 2 end of file

SEEK_SET 0 Beginning of file

void function5()
{
    
	FILE* pfile;
	char str[100] = {
    };
	if ((pfile = fopen("text5.txt", "r")) != NULL)
	{
    
		printf(" File opened successfully !\n");
	}
	else
	{
    
		printf(" File opening failure !\n");
	}
	//  Normal read 
	putchar(fgetc(pfile));
	putchar('\n');
/* C  Library function  int fseek(FILE *stream, long int offset, int whence)  Set flow  stream  The file location for the given offset  offset,  Parameters  offset  Means from a given  whence  Number of bytes for location lookup .  Parameters : stream --  This is pointing to  FILE  Object pointer , The  FILE  Object identifies the stream . offset --  This is relative  whence  The offset , In bytes . whence --  This is the beginning of adding an offset  offset  The location of . It is generally specified as one of the following constants : SEEK_SET  Beginning of file  SEEK_CUR  The current location of the file pointer  SEEK_END  End of file  #define SEEK_CUR 1 #define SEEK_END 2 #define SEEK_SET 0  Return value :  If it works , Then the function returns zero , Otherwise, a nonzero value is returned . */
    fseek(pfile, 2, SEEK_END); // Make the file pointer point to the specified location 
	fgets(str, 6, pfile);
/* C  Library function  int ferror(FILE *stream)  Test a given stream  stream  Error identifier for .  Parameters : stream --  This is pointing to  FILE  Object pointer , The  FILE  Object identifies the stream .  Return value :  If the error identifier associated with the stream is set , This function returns a non-zero value , Otherwise, it returns a zero value . */
    if (ferror(pfile))
	{
    
		printf(" File read failed !\n");
	}
	else
	{
    
		printf(" File read successful !\n");
	}
	//  Print what you read 
	puts(str);
/*  describe  C  Library function  void clearerr(FILE *stream)  Clear the given stream  stream  End of file and error identifier .  Parameters  stream --  This is pointing to  FILE  Object pointer , The  FILE  Object identifies the stream .  Return value   It won't fail , And no external variables are set  errno,  But if it detects that its parameters are not a valid stream , Then return to  -1, And set up  errno  by  EBADF. */
	clearerr(pfile); // Clear read / write in /ferror An error flag appears after the function reports an error 
/*  describe  C  Library function  void rewind(FILE *stream)  Set the file location to the given stream  stream  The beginning of the file .  Parameters  stream --  This is pointing to  FILE  Object pointer , The  FILE  Object identifies the stream .  Return value   This function does not return any value . */
	rewind(pfile);// Force the file pointer to point to the beginning of the file 
/*  describe  C  Library function  int feof(FILE *stream)  Test a given stream  stream  End of file identifier .  Parameters  stream --  This is pointing to  FILE  Object pointer , The  FILE  Object identifies the stream .  Return value   When the end of file identifier associated with the stream is set , This function returns a non-zero value , Otherwise return to zero . */
	while (!feof(pfile)) //feof Function to determine whether to read to the end of the file 
	{
    
		putchar(fgetc(pfile));
	}
	putchar('\n');
	if (fclose(pfile) == EOF)
	{
    
		printf(" File close failed !\n");
	}
	else
	{
    
		printf(" File closed successfully !\n");
	}
}
原网站

版权声明
本文为[MuShan-bit]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011339286229.html