简体   繁体   English

fprintf不适用于c中的scanf

[英]fprintf not works with scanf in c

this is a part of my code. 这是我的代码的一部分。 this is very simple but when i open log.txt there isn't anything on this 这很简单,但是当我打开log.txt时,没有任何内容

int main()
{

    FILE *fp = fopen("log.txt", "w+");
    fprintf(fp, "%s\t%s\t%s\n", "Date", "Time Execution Time(ms)", "/path");
    char path[200];
    while (1)
    {

        printf("enter path : ");
        scanf("%s", &path);

        fprintf(fp, "%d-%d-%d %d:%d:%d\t%ld\t%s\n", tm.tm_year + 1900,
                tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
                elapsed, path);
    }
}

but with this change is work 但是有了这个改变才是工作

int main()
{

    FILE *fp = fopen("log.txt", "w+");
    fprintf(fp, "%s\t%s\t%s\n", "Date", "Time Execution Time(ms)", "/path");
    char path[200];

    printf("enter path : ");
    scanf("%s", &path);

    fprintf(fp,"%d-%d-%d %d:%d:%d\t%ld\t%s\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,elapsed,path);
}  

and this code works too : 并且此代码也适用:

int main()
{

    FILE *fp = fopen("log.txt", "w+");
    fprintf(fp, "%s\t%s\t%s\n", "Date", "Time Execution Time(ms)", "/path");

    while (1)
    {

        fprintf(fp, "%d-%d-%d %d:%d:%d\t%ld\t%s\n", tm.tm_year + 1900,
                tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
                elapsed, "kkjk");
    }
}

but i don't know why first code not works . 但我不知道为什么第一个代码不起作用。 please help me 请帮我

You are running into a buffering problem. 您正在遇到一个缓冲问题。

In your second example, where the application quits, there is an implicit fclose() that will write all data to disk for you. 在第二个示例中,应用程序退出,其中有一个隐式的fclose() ,它将为您将所有数据写入磁盘。

Try adding fflush(fp) after your writes in the loop, to force a flush of any pending writes. 尝试在循环中写入后添加fflush(fp) ,以强制刷新所有未决的写入。

Or look at setvbuf() if you want to disable / change the buffering. 或者,如果要禁用/更改缓冲,请查看setvbuf() Try adding setlinebuf(fp) after your fopen() , to make the steam line buffered - effectively the system will call fflush() on your behalf when a new line ( \\n ) is written. 尝试在fopen() setlinebuf(fp)之后添加setlinebuf(fp) ,以缓冲蒸汽行-有效地,当写入新行( \\n )时,系统将代表您调用fflush()

The reason that your last program works is that you're filing the default block buffer very quickly, and carrying on. 您上一个程序起作用的原因是,您非常快地提交了默认的块缓冲区,然后继续进行。 If you check, the file will not actually be in sync with where you think it is until that next block has been filled and written to disk. 如果您进行检查,则该文件实际上不会与您认为的位置同步,直到下一个块被填充并写入磁盘为止。 You can try this by running your first example again. 您可以通过再次运行第一个示例来尝试此操作。 This time give lots of input - eventually you'll see a whole load of data appears in the file, then nothing, nothing , and then lots more. 这次提供了很多输入-最终,您会看到整个数据负载出现在文件中,然后什么都没有,什么都没有 ,然后还有更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM