我在尝试运行这个程序时遇到了一些问题我正在努力...要求说我不允许使用排序功能......我自己做了一些事情......等等。
差不多,程序编译但执行后挂起......我猜它已陷入无限循环......但我似乎无法找到它...... :(
该程序读取已经被排序最少的数据文件并将它们(有序)合并到第三个.txt文件中......
这两个文件是Data1.txt和Data2.txt 包含:
DATA1.TXT
2
2
2
2
Data2.txt
1
3
5
7
9
combine.c
#include <stdio.h>
#include <stdlib.h>
void sortData(FILE *fpData1, FILE *fpData2)
{
int n, m;
FILE *fpMerge;
fpMerge = fopen("Merge.txt", "w+");
fscanf(fpData2, "%i", &n);
fscanf(fpData1, "%i", &m);
while(n != EOF || m != EOF)
{
if(n == EOF)
{
fscanf(fpData1, "%i", &m);
while(m != EOF)
{
fprintf(fpMerge, "%i\n", m);
fscanf(fpData1, "%i", &m);
}
}
if(m == EOF)
{
fscanf(fpData2, "%i", &n);
while(n != EOF)
{
fprintf(fpMerge, "%i\n", n);
fscanf(fpData2, "%i", &n);
}
}
if(n < m)
{
fprintf(fpMerge, "%i\n", n);
fscanf(fpData2, "%i", &n);
}
if(n > m)
{
fprintf(fpMerge, "%i\n", m);
fscanf(fpData1, "%i", &m);
}
if(n == m)
{
fprintf(fpMerge, "%i\n", n);
fprintf(fpMerge, "%i\n", m);
fscanf(fpData2, "%i", &n);
fscanf(fpData1, "%i", &m);
}
}
fclose(fpMerge);
}
int main (void)
{
FILE *fpData1;
FILE *fpData2;
fpData1 = fopen("Data1.txt", "r");
if(fpData1 == NULL)
{
printf("There was an error opening the file...program terminating..\n");
exit(1);
}
fpData2 = fopen("Data2.txt", "r");
if(fpData2 == NULL)
{
printf("There was an error opening the file...program terminating..\n");
exit(1);
}
sortData(fpData1, fpData2);
fclose(fpData1);
fclose(fpData2);
return 0;
}
答案 0 :(得分:7)
您不想比较n != EOF
,而是fscanf
的返回值:
int count_1;
count_1 = fscanf(fpData1, "%i", &m);
if (count_1 == EOF) // EOF (or error)
{
// ...
}
fscanf
也会在出错时返回EOF
。如果您需要分开EOF和错误条件,请使用ferror(fpData1)
,然后查找错误代码(存储在errno
中)。
答案 1 :(得分:1)
您对EOF的测试不太正确
void sortData(FILE *fpData1, FILE *fpData2)
{
int data1;
int data2;
FILE *fpMerge;
fpMerge = fopen("Merge.txt", "w+");
fscanf(fpData1, "%i", &data1);
fscanf(fpData2, "%i", &data2);
// While one file still has data
while(!feof(fpData1) && !feof(fpData2))
{
// Choose 1 file to test
// Read from that file and put into merge file until either we
// run out of data or the condition fails.
if(data1 < data2)
{
do {fprintf(fpMerge, "%i\n", data1);}
while ((fscanf(fpData1, "%i", &data1) != 0) && (data1 <= data2));
}
else
{
do {fprintf(fpMerge, "%i\n", data2);}
while ((fscanf(fpData2, "%i", &data2) != 0) && (data2 <= data1));
}
// NOTE: if fscanf() returns 0 it has failed to read (EOF)
}
// One of the files has reached the EOF
// Dump the other file.
while(fscanf(fpData1, "%i", &data1) != 0) {fprintf(fpMerge, "%i\n", data1);}
while(fscanf(fpData2, "%i", &data2) != 0) {fprintf(fpMerge, "%i\n", data2);}
}
答案 2 :(得分:1)
EOF 不是角色。
EOF 不是整数。
任何文件都不会包含 EOF (char
和int
)。
EOF 是一个条件 文件将处于该条件或(通常)不是。
您应该检查fscanf()
的返回值以检测 EOF 或其他问题。