C++ method of reading a file into an array and then reading an array

  • 2020-06-07 04:55:54
  • OfStack

As shown below:


<pre name="code" class="cpp">#include<iostream> 
#include<fstream> 
using namespace std;
#define MAX_PACK_SIZE 10240
void main() 
{ 
 char filePath[256]; 
 strcpy(filePath,"F:/ video /1.mp4");  // Access path  
 FILE *pFile; 
 pFile=fopen(filePath,"r+b"); 
	if(pFile==NULL)
	{
		cout<<" Failed to open file "<<endl;
		return ;
	}
 fseek(pFile,0,SEEK_END); 
 // long nLength=ftell(pFile); // Get file length (number of bytes) 
	_int64 nLength=_ftelli64(pFile); // Gets the maximum length 2 the 64 To the power -1 bytes 
	cout<<" The file length is: "<<nLength<<endl;
	if(nLength==-1)  // Read error 
	{
		return;
	}
 char buff[MAX_PACK_SIZE+1];  // Used to store part of file data 
	char filePath1[256];
	strcpy(filePath1,"E:/ The picture /Saved Pictures/8.mp4");
	FILE *File;
	File=fopen(filePath1,"a+b"); // Open the file to append And the way to read, if there is no file created 
	fseek(pFile,0,SEEK_SET);  // Locate the starting position 
 for(_int64 i=0;i+MAX_PACK_SIZE+1<nLength;i+=MAX_PACK_SIZE)
	{
		if(i+MAX_PACK_SIZE+1<nLength)
		{
   fread(buff,sizeof(char),MAX_PACK_SIZE,pFile); // Reads from the current location of the file MAX_PACK_SIZE bytes 
		 fseek(pFile,0,SEEK_CUR);  // Orientation to the upper 1 Step positioning position plus MAX_PACK_SIZE The location of the 
		 fwrite(buff,sizeof(char),MAX_PACK_SIZE,File); // will buff Add data to File In the 
		}
		else
		{
			fread(buff,sizeof(char),nLength-i,pFile);
			fseek(pFile,0,SEEK_CUR);
			fwrite(buff,sizeof(char),nLength-i,File);
		}
	}
	fclose(pFile);  // Close the file 
	fclose(File);
} 

Related articles: