gpt4 book ai didi

c - 如何在C中将一个文件拆分成多个文件?

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:43 26 4
gpt4 key购买 nike

我正在尝试将一个文件拆分成多个较小的文件。问题是如果大小(用户提供的)大于缓冲区,程序就会崩溃,否则它可以正常工作。谁能帮忙?这是代码:

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 );

类似的东西。除了一些错误,但你明白了。这是家庭作业吗?

关于c - 如何在C中将一个文件拆分成多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25910566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com