C language - file operation

What are the files in C language

The so-called file is a collection of data stored in external media (such as. TXT. BMP. Jpg. Exe. Rmvp, etc.). These files have their own purposes. We usually store them on disk or removable media.

Three elements of a file: file path, file name and suffix.

Predefined standard flow:

  1. stdin is a FILE * type expression associated with the standard input stream
  2. stdout is a FILE * type expression associated with the standard output stream
  3. stderr is a FILE * type expression associated with the standard error output stream

The concept of flow: the abstract "standard logic device" or "standard file" is usually called "flow".

Flow can be divided into input flow and output flow according to direction
According to the data form, it can be divided into text stream and binary stream

The C language operation file is divided into three steps: (it can be associated with the three steps of locking the elephant in the refrigerator)

  1. Open file
  2. Read write file
  3. Close file

Open file function prototype

FILE* fwrite= fopen(const char *filename,const char* mode)
/*
Return value: after successful opening, the pointer of the FILE type corresponding to the FILE is returned; Failed to open, NULL returned.
Therefore, it is necessary to define a pointer variable of FILE type and save the return value of the function.
You can judge whether the file is opened successfully according to the return value of this function.
*/
if(fwrite==nullptr)
{
    printf("file open fail!");
    exit(1);
}

filename: file name, which can include path or not. Excluding path means that the file in the current directory is operated

Mode: file opening mode, indicating the operations that can be performed on the file. Common operation modes are 'r', 'W', 'a'; Note that the difference between W and a is that a is appended at the end, while W is completely rewritten. Pay attention to the operation of documents and use w with caution.

Prototype of the close function fclose: int fclose(FILE* strem)

Parameters:
Stream: pointer to the stream object to close

Return value:
If the stream is successfully closed, a value of 0 is returned. If failed, EOF(-1) is returned.
Even if the call fails, the stream passed as a parameter is no longer associated with the file or its buffer.

fclose (fwrite);

String formatting function: int sprintf(char str,const charformat,...)

Parameters:
str: pointer to the buffer, which should be large enough
Format: format string, which follows the same specification as that in printf.
...: variable parameters

Return value: returns the length of the written string if successful. Negative value if unsuccessful.

int main()
{
   int a=10,int b=20;
   char buffer[16];
   int len=0;
   len=sprintf(buffer,"a = %d,b = %d\n",a,b);
   //len=13
   return 0;
}

Format write function: int fprintf (FileStream, const charformat,...);

Normal output function: int printf(const char *format,...);

example:

#include <stdio.h>

int main()
{
   int ar[]={12,23,34,45,56,67,78,89,90,100};
   int n=sizeof(ar)/sizeof(ar[0]);
   int i=0;
   FILE*fpw=fopen("Test.txt","w");
   if(nullptr==fpw)
   {
     printf("open file failter\n");
     exit(EXIT_FAILURE);
   }
   for(i=0;i<n;++i)
   {
     fprintf(fpw,"%d",ar[i]);
   }
   fclose(fpw);
   fpw=nullptr;
   return 0;
}

Read formatted data from stream function: int fscanf_s(FILE* stream,const char *format,…)

example:

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

int main()
{
	const int n = 10;
	int ar[n] = { 0 };
	FILE* fpr = fopen_s("Test.txt", "r");
	if (nullptr == fpr)
	{
		printf("open file failter\n");
		exit(EXIT_FAILURE);
	}
	for (int i = 0; i < n; ++i)
	{
		fscanf_s(fpr, "%d", ar[i]);
	}
	fclose(fpr);
	fpr = nullptr;
	return 0;
}

Reading and writing of binary files

Write function: size_t fwrite(const void ptr,size_t size,size_t count ,FILE stream)

Readout function: size_t fread(const void ptr,size_t size,size_t count ,FILE stream)

#include <stdio.h>
#include <cstdlib>

#define ARSIZE 10
void save_ar(int* ar, int n)
{
	FILE* fpw = NULL;
	int len = 0;
	if (NULL == ar || n < 1)return;
	fpw = fopen("Test2.txt", "wb");
	if (NULL == fpw)
	{
		printf("open file failure\n");
		exit(EXIT_FAILURE);
	}
	len = fwrite(ar, sizeof(ar), n, fpw);
	fclose(fpw);
	fpw = nullptr;
 }

void Load_ar(int* br, int n)
{
	FILE* fpr = NULL;
	int len = 0;
	if (NULL == br || n < 1)return;
	fpr = fopen("Test.txt", "rb");
	if (NULL == fpr)
	{
		printf("open file failer!");
		exit(EXIT_FAILURE);
	}
	len = fread(br, sizeof(int), n, fpr);
	fclose(fpr);
	fpr = NULL;
}
int main()
{
	int ar[ARSIZE] = { 12,23,34,45,56,67,78,89,90,100 };
	int br[ARSIZE] = { 0 };
	int n = ARSIZE;
	save_ar(ar, n);
	Load_ar(br, n);
	return 0;
}

Keywords: C C++

Added by cap2cap10 on Fri, 04 Mar 2022 19:10:06 +0200