【问题标题】:Stuck in a loop using file management in C在 C 中使用文件管理陷入循环
【发布时间】:2017-10-05 21:04:39
【问题描述】:

程序是:

两个文件 DATA1 和 DATA2 包含排序的整数列表/编写程序来生成第三个文件 DATA,其中包含这两个列表的单个排序的合并列表。使用命令行参数指定文件名。

#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 编译器中使用命令“gcc file.c”编译。编译后运行程序,显示文件f1的内容,但不显示文件f2的内容。我似乎陷入了一个循环,因为 Ctrl + D 不起作用。所以我必须终止程序。

输出是:

对于第一个数据:
0, 2, 4, 6, 8, 10,
对于第二个数据:
^Z
[6]+ 停止./a.out

现在这里有什么问题。我以与打印 f1 的整数相同的方式打印了 f2 的整数,但为什么问题只出现在文件 f2 中?

【问题讨论】:

  • 我希望你知道 Ctrl-Z 不会终止程序,它只是暂停它。
  • for(;some condition;) 不是真正的代码。
  • @melpomene 现在我知道了 Ctrl-Z。谢谢。而且我知道我不应该设置“某些条件”,但我这样做是为了检查程序是否正在运行。
  • @manshu 这没有任何意义。您的代码甚至无法编译。
  • @melpomene 我在我的代码中创建了无限循环:p

标签: c file loops gcc file-management


【解决方案1】:

你的代码应该输出:

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); 

看看我的意思。换行符会刷新输出缓冲区本身,因此您可以使用任何一种方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多