我的意圖是獲取文件multiples.txt
上存在的所有數字,並寫出所需整數的倍數(由用戶輸入)。從文件中獲取倍數並在另一個文件上覆制
#include <stdio.h>
int main() {
FILE *f, *fs;
int value, multiple, n;
f = fopen("multiples.txt", "r");
if (f == NULL)
printf("Error\n");
fs = fopen("exit.txt", "w");
if (fs == NULL)
printf("Error\n");
printf("Write a number\n");
scanf("%d", &value);
do {
n = fscanf(f, "%d", multiple);
if (multiple % value == 0) {
fprintf(fs, "%d", multiple);
}
} while (n != EOF);
fclose(f);
fclose(fs);
}
我的程序崩潰,我無法確定它來自哪裏。
此外,fscanf在文件結束時不返回EOF。它返回匹配元素的數量。 –
我認爲fscanf會返回你得到的數量。 我推薦你 while(fscanf(f,「%d」,&multiple)== 1){//你想要什麼。 } :) – arubirate
請參閱http://www.cplusplus.com/reference/cstdio/fscanf/?kw=fscanf並返回值部分 – arubirate