一个简单但有效的方法是完全避免读入内存,只需执行以下操作:
while ((input_char = fgetc(input_fp)) != EOF)
{
if (input_char != specificByte)
{
fputc(input_char, output_fp);
}
else
{
/* do something with input_char */
}
}
这在理论上是低效的,因为您一次从缓冲区读取一个字符,这可能会很昂贵。然而,对于许多应用程序来说,这将运行得很好,特别是因为文件读取由 C 标准库缓冲。
如果您确实关心效率并希望最大限度地减少对文件函数的调用,请使用以下内容。
/* Don't loop through the chars just to find out the file size. Instead, use
* stat() to find out the file size and allocate that many bytes into array.
*/
char* array = (char*) malloc(file_size);
fread(array, sizeof(char), file_size, input_fp);
/* iterate through the file buffer until you find the byte you're looking for */
for (char* ptr = array; ptr < array + file_size; ptr++);
{
if (*ptr == specificByte)
{
break;
}
}
/* Write everything up to ptr into the output file */
fwrite(array, sizeof(char), ptr - array, output_fp);
/* ptr now points to the byte you're looking for. Manipulate as desired */