如果您正在从文件中读取,那么最好使用 fgets。这会自动为下一个 fget 移动文件指针。
fseek 和 ftell 正在减慢代码中的速度。尝试这个。它应该快得多。
#include <stdio.h>
#include <stdlib.h>
int
main()
{
char line[132];
int line_num = 0;
FILE *fp_r, *fp_w1, *fp_w2, *fp_w;
fp_r = fopen("readfile", "r");
if (fp_r == NULL) {
printf("Could not open testfile\n");
exit(0);
}
fp_w1 = fopen("writefile1", "w");
if (fp_w1 == NULL) {
printf("Could not open writefile1\n");
exit(0);
}
fp_w2 = fopen("writefile2", "w");
if (fp_w1 == NULL) {
printf("Could not open writefile2\n");
exit(0);
}
while (fgets(line, sizeof(line), fp_r) != NULL) {
line_num++;
if (*(line+9) == '0') {
fp_w = fp_w1;
}
else if (*(line+9) == '1') {
fp_w = fp_w2;
}
else {
printf("Exiting - Error at line %d\n", line_num);
exit(1);
}
fprintf(fp_w, line);
}
fclose(fp_r);
fclose(fp_w1);
fclose(fp_w2);
exit(0);
}
我使用的读取文件是
01234567 0 This is the line with 0 at position 10
01234567 1 This is the line with 1 at position 10