[英]C program: How to read from one file and write into another? Indexing
[英]how to write one binary file to another in c
我有一些二進制文件,我想寫入輸出文件。 所以我用一個char
作為緩沖器寫了這個函數天真地認為它會起作用。
//Opened hOutput for writing, hInput for reading
void faddf(FILE* hOutput, FILE* hInput) {
char c;
int scan;
do{
scan = fscanf(hInput, "%c", &c);
if (scan > 0)
fprintf(hOutput, "%c", c);
} while (scan > 0 && !feof(hInput));
}
執行此函數為我提供了開頭二進制文件中幾個可讀char
的輸出。 所以我這樣試了:
void faddf(FILE* hOutput, FILE* hInput) {
void * buffer;
int scan;
buffer = malloc(sizeof(short) * 209000000);
fread(buffer, sizeof(short), 209000000, hInput);
fwrite(buffer, sizeof(short), 209000000, hOutput);
free(buffer);
}
這“工作”,但僅在文件小於我的“幻數”時才有效嗎?有更好的方法嗎?
您應該避免每字節讀取字節數 。 使用fgets()
函數而不是fscanf().
當您打開彼此相鄰的兩個文件(輸入一個/輸出一個)時,您說輸出文件只包含可讀字符......但是您的文本編輯器是否可以在輸入文件上顯示不可讀的字符?
我不應該首先問這個問題,但這是我最終如何做到的:
void faddf(FILE* hOutput, FILE* hInput) {
void * buffer;
int scan,size;
size_t read;
//get the input file size
fseek(hInput, 0L, SEEK_END);
size = ftell(hInput);
fseek(hInput, 0L, SEEK_SET);
//place the get space
buffer = malloc(size);
if (buffer == NULL)exit(1);//should fail silently instead
//try to read everything to buffer
read = fread(buffer, 1, size, hInput);
//write what was read
fwrite(buffer, 1, read, hOutput);
//clean up
free(buffer);
}
雖然您的新代碼(在答案中 )比舊代碼好得多,但它仍然可以改進和簡化。
具體來說,您可以通過以塊的形式復制文件來避免任何內存問題。
void faddf( FILE *fpout, FILE *fpin )
{
char buffer[4096];
size_t count;
while ( (count = fread(buffer, 1, sizeof buffer, fpin)) > 0 )
fwrite(buffer, 1, count, fpout);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.