简体   繁体   中英

Cannot write to file in C program

I'm trying to write my results to an outputfile, running this C program i Mac Terminal. I have checked that all parts of the program works by writing directly to the terminal, but when I'm trying to write to file, nothing happens.

The "writing to file" line writes on every iteration, however nothing happens to the outputdata.txt file.

I've changed the permissions, and I'm able to write to this file directly from the terminal. However, it doesn't work using the below code.

#define OUTPUTFILE "outputdata.txt"

FILE *ofp;

char ofile_name[50] = OUTPUTFILE;

ofp = fopen(ofile_name, "r");

for (p = 1; p <= NumPattern ; p++) {
    for (k = 1 ; k <= numnodes_out ; k++) {
        fprintf(ofp, "%f\n", output_nodes[p][k]);
        fprintf(stdout, "Writing to file\n");
    }
}
fclose(ofp);

You're opening the file in read mode, see https://linux.die.net/man/3/fopen .

If you want to write to the file you have to open the file with a mode that supports writing, for example: fopen(ofile_name, "w") .

Your primary options if you only want to write to the file are:

  1. "w", which will create the file if it does not exist, otherwise it will truncate the file to 0 length (remove everything in the file) and allow you to write to it; or,
  2. "a", which will append to the end of an existing file.

Additionally, if you look at the link previously mentioned, you should note that the function could return null if the file does not open successfully. Because of this you should check if the FILE* returned by fopen is not null before operating on it.

#define OUTPUTFILE "outputdata.txt"

FILE *ofp;

char ofile_name[50] = OUTPUTFILE;

ofp = fopen(ofile_name, "r");

if (ofp) { // NOTE: added NULL check.
    for (p = 1; p <= NumPattern ; p++) {
        for (k = 1 ; k <= numnodes_out ; k++) {
            fprintf(ofp, "%f\n", output_nodes[p][k]);
            fprintf(stdout, "Writing to file\n");
        }
    }
    fclose(ofp);
}

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