简体   繁体   中英

Cannot write to a file

I have a weird problem , I'm building a C socket server, and I have 2 files included in my server,

in one of the files I'm trying to write to a file I create, so I have the server.c in my server.c I have Dir.c that contains only this function which is :

void writeFile(){
    FILE* f;
    f=fopen("test.txt","w");
    fputs("hello",f); 
}

now for the hell of it, It creates the file but when I open it its empty, but when I copy this code to a different file and run it there, I get my file with the value hello written in it, I have absolutely no idea why this is happening, this is how I compile my program:

 gcc   Dir.c server.c -lpthread -o server

I would love some help because I'm clueless...

Assuming your server keeps running after running your function writeFile you don't close your output file. The output is in the cache and not yet written to the file.

When your program exits the file is automatically closed. This is probably the difference when you use this code in some other program.

Add fclose(f); after fputs("hello",f); to close the file.

As mentioned in the comments you should always check the return code of the functions and handle errors.

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