C and C++ method of reading and writing text files binary files

  • 2020-06-07 04:57:48
  • OfStack

Purpose 1:

Master C language text file reading and writing mode;

Master C language base 2 file reading and writing mode;

Master CPP text file reading and writing mode;

Master CPP2 base file reading and writing mode;

2: C language text file read and write

1. Write text files


// using C Patterns of Txt To write 
void TxtWrite_Cmode()
{
	// To prepare data 
	int index[50] ;
	double x_pos[50], y_pos[50];
	for(int i = 0; i < 50; i ++ )
	{
		index[i] = i;
		x_pos[i] = rand()%1000 * 0.01 ;
		y_pos[i] = rand()%2000 * 0.01;
	}
	// Write out the txt
	FILE * fid = fopen("txt_out.txt","w");
	if(fid == NULL)
	{
		printf(" Failed to write file! \n");
		return;
	}
	for(int i = 0; i < 50; i ++ )
	{
		fprintf(fid,"%03d\t%4.6lf\t%4.6lf\n",index[i],x_pos[i],y_pos[i]);
	}
	fclose(fid);
}

2. Text file reading


// using C Patterns of Txt read 
void TxtRead_Cmode()
{
	FILE * fid = fopen("txt_out.txt","r");
	if(fid == NULL)
	{
		printf(" Open the %s failure ","txt_out.txt");
		return;
	}
	vector<int> index;
	vector<double> x_pos;
	vector<double> y_pos;
	int mode = 1;
	printf("mode for 1 , read and output according to the character; mode for 2 , read in the output by line; mode for 3 , knows the data format, reads in and outputs by line \n");
	scanf("%d",&mode);
	if(mode == 1)
	{
		// Read in by character and output directly 
		char ch;  // Read the character, judging criteria is ch Does not equal the end character EOF ( end of file ) 
		while(EOF!=(ch= fgetc(fid)))
			 printf("%c", ch); 
	}
	else if(mode == 2)
	{
		char line[1024];
		memset(line,0,1024);
		while(!feof(fid))
		{
			fgets(line,1024,fid);
			printf("%s\n", line); // The output 
		}
	}
	else if(mode == 3)
	{
		// Knowing the data format, read in and store the output on a row 
		int index_tmp;
		double x_tmp, y_tmp;
		while(!feof(fid)) 
		{ 
			fscanf(fid,"%d%lf%lf\n",&index_tmp, &x_tmp, &y_tmp);
			index.push_back(index_tmp);
			x_pos.push_back(x_tmp);
			y_pos.push_back(y_tmp);
		}
		for(int i = 0; i < index.size(); i++)
			printf("%04d\t%4.8lf\t%4.8lf\n",index[i], x_pos[i], y_pos[i]);
 
	}
	fclose(fid);
}

3: C language base 2 files read and write

1. 2 base file write


// using C Pattern to write 2 A binary file 
void DataWrite_CMode()
{
	// To prepare data 
	double pos[200];
	for(int i = 0; i < 200; i ++ )
		pos[i] = i ;
	// Write the data 
	FILE *fid;
	fid = fopen("binary.dat","wb");
	if(fid == NULL)
	{
		printf(" Error writing file ");
		return;
	}
	int mode = 1;
	printf("mode for 1 , write one by one; mode for 2 , line by line \n");
	scanf("%d",&mode);
	if(1==mode)
	{
		for(int i = 0; i < 200; i++)
			fwrite(&pos[i],sizeof(double),1,fid);
	}
	else if(2 == mode)
	{
		fwrite(pos, sizeof(double), 200, fid);
	}
	fclose(fid);
}

2.2 Base file reading


// using C Read mode 2 A binary file 
void DataRead_CMode()
{
	FILE *fid;
	fid = fopen("binary.dat","rb");
	if(fid == NULL)
	{
		printf(" Error reading file ");
		return;
	}
	int mode = 1;
	printf("mode for 1 , know pos How many are there; mode for 2 And don't know pos How many \n");
	scanf("%d",&mode);
	if(1 == mode)
	{
		double pos[200];
		fread(pos,sizeof(double),200,fid);
		for(int i = 0; i < 200; i++)
			printf("%lf\n", pos[i]);
		free(pos);
	}
	else if(2 == mode)
	{
		// Get file size 
		fseek (fid , 0 , SEEK_END);  
		long lSize = ftell (fid); 
		rewind (fid); 
		// Open up storage space 
		int num = lSize/sizeof(double);
		double *pos = (double*) malloc (sizeof(double)*num); 
		if (pos == NULL) 
		{ 
			printf(" Open space error "); 
			return; 
		} 
		fread(pos,sizeof(double),num,fid);
		for(int i = 0; i < num; i++)
			printf("%lf\n", pos[i]);
		free(pos);  // Free memory 
	}
	fclose(fid);
}

4: C++ text file read and write

1. Write text files


// using CPP Pattern to write txt
void TxtWrite_CPPmode()
{
	// To prepare data 
	int index[50] ;
	double x_pos[50], y_pos[50];
	for(int i = 0; i < 50; i ++ )
	{
		index[i] = i;
		x_pos[i] = rand()%1000 * 0.01 ;
		y_pos[i] = rand()%2000 * 0.01;
	}
	// Write out the txt
	fstream f("txt_out.txt", ios::out);
	if(f.bad())
	{
		cout << " Error opening file " << endl;
		return;
	}
	for(int i = 0; i < 50; i++)
		f << setw(5) << index[i] << "\t" << setw(10) << x_pos[i] <<"\t" <<setw(10)<< y_pos[i] << endl;
	f.close();
 
}

2. Text file reading


// using CPP Read mode txt
void TextRead_CPPmode()
{
	fstream f;
	f.open("txt_out.txt",ios::in);	
	// File opening options: 
	// ios::in    = 0x01, // Read, create if the file does not exist (ifstream Default open mode )
	// ios::out    = 0x02, // For writing, a file is created if it does not exist, and the original contents are cleared if the file already exists (ofstream Default open mode )
	// ios::ate    = 0x04, // When the file is opened, the pointer is at the end of the file. Can change the pointer position, constant and in , out A combination of 
	// ios::app    = 0x08, // For writing, if the file does not exist, it will be created. If the file already exists, the new content will be written after the content of the original file. The pointer position is always at the end 
	// ios::trunc   = 0x10, // Truncate the file length to before reading or writing 0 (the default) 
	// ios::nocreate = 0x20, // An error occurs when a file does not exist in or app A combination of 
	// ios::noreplace = 0x40, // An error occurred while the file was present out A combination of 
	// ios::binary  = 0x80  //2 Base format file 
	vector<int> index;
	vector<double> x_pos;
	vector<double> y_pos;
	if(!f)
	{
		cout << " Error opening file " << endl;
		return;
	}
	cout<<"mode for 1 , read and output according to the character; mode for 2 , read in the output by line; mode for 3 , knows the data format, reads in and outputs by line "<<endl;
	int mode = 1;
	cin>>mode;
	if(1== mode)
	{
		// Read in and output in bytes 
		char ch;
		while(EOF != (ch= f.get()))
			cout << ch;
	}
	else if(2 == mode)
	{
		// Read on a row and display 
		char line[128];
		int numBytes;
		f.getline(line,128);
		cout << line << "\t" << endl ;
		f.getline(line,128);
		cout << line << "\t" << endl ;
		f.seekg(0,0);							// Skip the byte 
		//seekg( Absolute position );      // Absolute movement, // Input stream operation 
		//seekg( The relative position , Reference position );  // Relative operation 
		//tellg();					 // Returns the current pointer position 
		while(!f.eof())
		{
			// use eof() The function checks if the file has finished reading 
			f.getline(line,128);
			numBytes = f.gcount();		// use gcount() Gets the actual number of bytes read 
			cout << line << "\t" << numBytes << " byte " << endl ;
		}
	}
	else if(3 == mode)
	{
		// If you know the data format, you can use it directly >> Read in 
		int index_temp = 0;
		double x_pos_temp = 0, y_pos_temp = 0;
		while(!f.eof())
		{
			f >> index_temp >> x_pos_temp >> y_pos_temp ;
			index.push_back(index_temp);
			x_pos.push_back(x_pos_temp);
			y_pos.push_back(y_pos_temp);
			cout << index_temp << "\t" << x_pos_temp << "\t" << y_pos_temp << endl;
		}
	}
	f.close();
}

5: C++2 base file read and write

1. 2 base file write


// using CPP Pattern to write 2 A binary file 
void DataWrite_CPPMode()
{
	// To prepare data 
	double pos[200];
	for(int i = 0; i < 200; i ++ )
		pos[i] = i ;
	// Write the data 
	ofstream f("binary.dat",ios::binary);
	if(!f)
	{
		cout << " File creation failed " <<endl;
		return;
	}
	f.write((char*)pos, 200*sizeof(double));  //fwrite In order to char * Write and do 1 A conversion 
	f.close();
}

2.2 Base file reading


// using CPP Read mode 2 A binary file 
void DataRead_CPPMode()
{
	double pos[200];
	ifstream f("binary.dat", ios::binary);
	if(!f)
	{
		cout << " Failed to read file " <<endl;
		return;
	}
	f.read((char*)pos,200*sizeof(double));
	for(int i = 0; i < 200; i++)
		cout << pos[i] <<endl;
	f.close();
 
}

6 summarizes

1. C language reading and writing files are operated by FILE pointer, in which text files are read and written by fprintf,fscanf, and 2 base files are read and written by fread,fwrite

C++ read and write files are operated by fstream, ifstream, ofstream, and text files are used < < and > > Use read and write to read and write files in base 2


Related articles: