【问题标题】:Problems with C file writingC文件写入问题
【发布时间】:2017-11-26 18:40:31
【问题描述】:

我在写入文件时遇到问题,这是代码:

#include <stdio.h>

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        printf("\x1B[31mError::%s takes exactly one argument!\n\x1B[0m",argv[0]);
        return 1;
    }

    char string[100];

    FILE* file=fopen(argv[1],"w");
    if(file==NULL)
    {
        printf("\x1B[31mFile is invalid!\x1B[0m\n");
        return 1;
    }

    while(!feof(stdin))
    {
        scanf("%s",string);
        fprintf(file,"%s\n",string);
    }
    fclose(file);
    return 0;
} 

它应该使用scanf输入并写入文件,直到我输入文件结尾字符(ctrl+Z),当它完成运行时,我打开的文件是空的。这个代码结构在deitel & deitel这本书里也有建议,你知道这里有什么问题吗? 另外,我想知道如何每次都用scanf而不是一个单词来使用整个短语..如果我这样做 scanf("%[^\n]",string) 程序变得混乱,一旦我写了一些东西,它就会进入一个循环,一遍又一遍地写同样的东西,文件会变得像 1.7Gb 一样大..帮助!

【问题讨论】:

  • 使用while (!feof(fp))总是错误的。
  • ctrl+Z 是 SIGTSTP 将强制停止进程执行,数据不会保存到文件中。
  • 原来 eof 键因操作系统而异,它是 ctrl+D 而不是 Z 谢谢,但我也想知道为什么 scanf("%[^\n]",string) 会不工作?

标签: c file io


【解决方案1】:

当用户按下ctrl+z 时,您的进程(a.out)将在内部收到signal20,您的进程将是stopped,但数据将保存not,因为程序已终止abnormally .

您可以在terminal 上键入man 7 signal 并检查ctrl+zdefault action。那么现在你需要修改ctrl+z by-default action 吗?如何 ?使用signal()sigaction()

每当按下ctrl+z 时,跳转到isr() 并使用save 系统调用save 获取当前进程状态。 ctrl+z 是无信号 20

我对你的代码做了一些小的修改。

#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void isr(int n)
{
        if(n == 20)//if ctrl+z is pressed then condition will be true 
        {
                printf("in isr :\n");
                exit(0);//exit(0) is normal termination of process i.e it will save current process context
        }
}
int main(int argc,char* argv[])
{
        if(argc!=2)
        {
                printf("\x1B[31mError::%s takes exactly one argument!\n\x1B[0m",argv[0]);
                return 1;
        }

        char string[100];

        FILE* file=fopen(argv[1],"w");
        if(file==NULL)
        {
                printf("\x1B[31mFile is invalid!\x1B[0m\n");
                return 1;
        }

        while(!feof(stdin))
        {
                signal(20,isr);//when user presses ctrl+z it will jump to isr()
                scanf("%s",string);
                fprintf(file,"%s\n",string);

        }

        fclose(file);
        return 0;
}

曾经浏览过signal()exit() 的手册页。

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多