在C中使用文件管理陷入循环
该计划是: 两个文件DATA1和DATA2包含整数的排序列表/编写一个程序以生成第三个文件数据,其中包含这两个列表的单个排序合并列表。使用命令行参数指定文件名在C中使用文件管理陷入循环,c,file,loops,gcc,file-management,C,File,Loops,Gcc,File Management,该计划是: 两个文件DATA1和DATA2包含整数的排序列表/编写一个程序以生成第三个文件数据,其中包含这两个列表的单个排序合并列表。使用命令行参数指定文件名 #include<stdio.h> //Two files DATA1 and DATA2 contain sorted lists of integers/ Write a program to produce a third file DATA which holds a single sorted, merged li
#include<stdio.h>
//Two files DATA1 and DATA2 contain sorted lists of integers/ Write a program to produce a third file DATA which holds a single sorted, merged list of these two lists. Use command line arguments to specify the file names.
void sort(FILE*, FILE*, FILE*);
main()
{
FILE *f1, *f2, *f;
int i;
f1=fopen("DATA1", "w"); //To set the sorted integers in file f1
for(i=0;i<=10; i=i+2)
putw(i, f1);
fclose(f1);
f2=fopen("DATA2", "w"); //To set the sorted integers in file f2
for(i=1;i<=11; i=i+2)
putw(i, f2);
fclose(f2);
printf("For first DATA:\n"); //To print the content of f1
f1=fopen("DATA1", "r");
while((i=getw(f1)) != EOF)
printf("%d, ", i);
fclose(f1);
printf("\nFor second DATA:\n"); //To print the content of file f2
f2=fopen("DATA2", "r");
while((i=getw(f2)) != EOF)
printf("%d, ", i);
fclose(f2);
sort(f1, f2, f); //To sort the integers from f1 and f2 and merge the sorted into file f
f=fopen("DATA", "r"); //To print the integers in file f
while((i=getw(f)) != EOF)
printf("%d, ", i);
fclose(f);
}
void sort(FILE *d1, FILE *d2, FILE *d)
{
int a, b;
d1=fopen("DATA1", "r");
d2=fopen("DATA2", "r");
d=fopen("DATA", "w");
a=getw(d1);
b=getw(d2);
for(;some condition;)
{
if(a>b)
{
int temp=a;
a=b;
b=temp;
b=getw(d2);
putw(a, d);
b=getw(d2);
}
else
{
putw(a, d);
a=getw(d1);
}
}
fclose(d1);
fclose(d2);
fclose(d);
}
现在,使用命令gcc file.c在gcc编译器中编译该程序。编译后,当我运行程序时,它会显示文件f1的内容,但不会显示文件f2的内容。我觉得它好像陷入了一个循环,因为Ctrl+D不起作用。所以我必须终止这个程序
输出为:
对于第一个数据:
0, 2, 4, 6, 8, 10,
第二个数据:
^Z
[6] 停止
现在这里的问题是什么。我打印f2的整数的方式与打印f1的整数的方式相同,但为什么问题只出现在文件f2中?您的代码应该输出:
For first DATA:
0, 2, 4, 6, 8, 10,
For second DATA:
1, 3, 5, 7, 9, 11,
这就是你需要的。我怀疑这个错误不久就发生了,并且输出缓冲区没有及时刷新,因此数据保存在那里,很可能没有在标准输出屏幕中显示
将代码更改为:
printf("\nFor second DATA:\n"); //To print the content of file f2
f2=fopen("DATA2", "r");
while((i=getw(f2)) != EOF)
printf("%d, ", i);
fclose(f2);
printf ("\n");
fflush(stdout);
sort(f1, f2, f);
明白我的意思。换行符会自动刷新输出缓冲区,因此您可以使用任何一种方法。我希望您知道Ctrl-Z不会终止程序,它只是暂停程序;某些条件;不是真正的代码。@melpomene现在我知道Ctrl-Z了。谢谢。我知道我不应该设置一些条件,但我这样做是为了检查程序是否在这一点上运行。@manshu这毫无意义。您的代码甚至没有编译。@melpomene我在代码中创建了无限循环:p