0

This is my code

#include <stdio.h> 
int main() 
{ 
FILE *file; 
file = fopen("file.txt","a+"); 

fprintf(file,"%s","test :)");
fclose(file); 

return 0; 
}

Don't understand why it won't create a txt file help

SamSam
  • 31
  • 2
  • 5
  • 1
    What goes wrong? What happens if you single-step through the execution? Add code to check that the `fopen()` succeeds, I/O can fail. – unwind Oct 31 '13 at 13:37
  • The expected behavior of the `a+` mode is to create the file if it does not exist. My hunch here is that the `fopen()` call fails for a specific reason (yes it can fail so always check the return value ...) – Rerito Oct 31 '13 at 13:38
  • check out your current working directory (look up getcwd and printf it or something). My guess is you might not have full permissions for the folder it is trying to create file.txt in, but like the guy below says it could be any number of things. If you want to change your current working directory, use chdir before your fopen, or hardcode the directory you want in the fopen, like fopen("C://users/me/documents/file.txt","a+"); – jacerate Oct 31 '13 at 20:11
  • yesterday it works but today not anymore... i did nothing... – SamSam Nov 13 '13 at 09:17

3 Answers3

1

Please try perror to check if you have permission to write to the file or not. That is the problem most of the time. Add this after fopen

if (!file)
perror("fopen");
azmuhak
  • 964
  • 1
  • 11
  • 31
  • i try it but it still not working with the if loop but iets prints nothing so i dont know T.T – SamSam Nov 13 '13 at 09:02
  • if you are using Visual Studio, just put a break point on the `FILE *file = fopen("file.txt","a+"); ` and debug it. See what happens to the file in the watch window when the cursor crosses this line and then update me here – azmuhak Nov 13 '13 at 10:07
1

You need to check for errors in your program. fopen() can fail for a variety of reasons. We can either inspect errno, or use perror / strerror to print a useful message.

#include <stdio.h> 
#include <stdlib.h>

int main() 
{ 
    FILE *file = fopen("file.txt","a+"); 
    if (file == NULL) {
        perror("Failed to open the file");
        exit(-1);
    }

    fprintf(file,"%s","test :)");
    fclose(file); 

    return 0; 
}

For example, if a file exists in the current directory, but is owned by a different user:

[8:40am][wlynch@watermelon /tmp] ./foo
Failed to open the file: Permission denied
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • i try it but it still not working with the if loop but iets prints nothing so i dont know T.T i have premission i think – SamSam Nov 13 '13 at 09:04
0

Create a file if one doesn't exist - C here are answers...The one that's under the marked one worked for me on my s.o. The way you are trying to do doesn't work on windows, but works on linux. Sorry for saying what I said before...Both operating systems have their bright and not so bright side.