简体   繁体   English

无法在 C 程序中写入文件

[英]Cannot write to file in C program

I'm trying to write my results to an outputfile, running this C program i Mac Terminal.我正在尝试将结果写入输出文件,并在 Mac 终端上运行此 C 程序。 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. “写入文件”行在每次迭代时写入,但 outputdata.txt 文件没有任何反应。

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 .您正在以读取模式打开文件,请参阅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") .如果要写入文件,则必须使用支持写入的模式打开文件,例如: 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; “w”,如果文件不存在,它将创建文件,否则它会将文件截断为 0 长度(删除文件中的所有内容)并允许您写入; or,或者,
  2. "a", which will append to the end of an existing file. “a”,将附加到现有文件的末尾。

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.此外,如果您查看前面提到的链接,您应该注意到如果文件未成功打开,该函数可能会返回 null。 Because of this you should check if the FILE* returned by fopen is not null before operating on it.因此,在对其进行操作之前,您应该检查 fopen 返回的 FILE* 是否不为空。

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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