1

First of all, this is my fist stack overflow question, so forgive me if I format this wrong.

I am a beginner at C, and I am up to a point in my book on File i/o. The following code, which is supposed to print the lines to test.txt, doesn't create a new txt file or... do anything.

I am running Code Blocks 16.01 on Windows. Is this code designed for another OS?

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

main() {
    FILE *fp;
    fp = fopen("/tmp/test.txt", "w+");
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);
}

Ok, so removing the slash makes it work. In the original code, it is 'fopen("/tmp/test.txt", "W+");' Shouldn't this create the file in folder tmp?

James A
  • 73
  • 11

2 Answers2

3

Try removing the front-slash from the file name. You seem to be doing everything properly, the slash might be the problem. If not, let us know.

Edit: When I wrote my comment your fopen used "/test.txt" and not "/temp/test.txt", do you have the "temp" folder created in the directory the application is running from? If not, try creating it. Or remove it altogether and try creating the text file within the directory the application is running from.

BartBB
  • 77
  • 8
1

Use double // in windows for navigate through directory.

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

int main() {
    FILE *fp;
    /* 
       file path in windows should be like this= C:\\users\\r.maurya\\Desktop\\Downloads\\file.txt 
    */
    fp = fopen("C:\\users\\r.maurya\\Desktop\\Downloads\\file.txt", "w+");
    fprintf(fp, "This is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);
return 0;//Optional, On success of program 
}
roottraveller
  • 7,942
  • 7
  • 60
  • 65