これを行う簡単で効果的な方法は、メモリへの読み込みをまったく回避し、次のことを行うことです。
while ((input_char = fgetc(input_fp)) != EOF)
{
if (input_char != specificByte)
{
fputc(input_char, output_fp);
}
else
{
/* do something with input_char */
}
}
これは、バッファから一度に 1 文字ずつ読み取るため、コストがかかる可能性があるため、理論的には非効率的です。ただし、多くのアプリケーションでは、特にファイルの読み取りが 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 */