简体   繁体   中英

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

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.

Try adding fflush(fp) after your writes in the loop, to force a flush of any pending writes.

Or look at setvbuf() if you want to disable / change the buffering. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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