我正在尝试将一个文件拆分成多个较小的文件。问题是如果大小(用户提供的)大于缓冲区,程序就会崩溃,否则它可以正常工作。谁能帮忙?这是代码:
char * buffer = (char *)malloc(400);
FILE *exsistingFile = fopen(filename,"rb");
do
{
/*reading from a file */
bytesRead = fread( buffer, sizeof( char ), size, exsistingFile );
/*exits if its 0 */
if (bytesRead == 0)
{
printf("The reading has finished or the file has no data inside\n");
return 0;
}
fileCount ++;
sprintf (newFileName,"%s%04i",output,fileCount);
/* opening the new file bye the name given by the user */
outputFile = fopen(newFileName,"w");
/*checking whether the file is opened or not*/
if ( !outputFile )
{
printf( "File %s cannot be opened for reading\n", filename );
return E_BAD_DESTINATION;
}
/*write to file from the buffer*/
fwrite(buffer,sizeof(char),bytesRead,outputFile);
/*closing the output file*/
fclose(outputFile);
} while ( bytesRead > 0 );
那么,malloc 一个与用户提供的大小一样大的缓冲区?或者只以 400 字节为单位读写,直到达到用户给定的大小。
char * buffer = (char *)malloc(400);
FILE *exsistingFile = fopen(filename,"rb");
do
{
fileCount ++;
sprintf (newFileName,"%s%04i",output,fileCount);
/* opening the new file bye the name given by the user */
outputFile = fopen(newFileName,"w");
/*checking whether the file is opened or not*/
if ( !outputFile )
{
printf( "File %s cannot be opened for writing\n", filename );
return E_BAD_DESTINATION;
}
int workSize = size;
while (workSize)
{
int chunkSize = workSize > 400 ? 400 : workSize;
/*reading from a file */
bytesRead = fread( buffer, sizeof( char ), chunkSize, exsistingFile );
workSize -= bytesRead;
/*exits if its 0 */
if (bytesRead == 0)
{
printf("The reading has finished or the file has no data inside\n");
return 0;
}
/*write to file from the buffer*/
fwrite(buffer,sizeof(char),bytesRead,outputFile);
}
/*closing the output file*/
fclose(outputFile);
} while ( bytesRead > 0 );
类似的东西。除了一些错误,但你明白了。这是家庭作业吗?
我是一名优秀的程序员,十分优秀!