gpt4 book ai didi

c - C 中的 fprintf() 函数无法正常工作

转载 作者:行者123 更新时间:2023-11-30 18:46:30 25 4
gpt4 key购买 nike

我编写此代码是为了输入用户的数字并将其输出到文件中。但它不起作用,运行代码后,output.txt 文件仍然为空。请告诉我哪里做错了。我确保在运行程序之前已创建了 output.txt 文件,因此文件指针不会为NULL

#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE *ptr;ptr=fopen("output.txt","rw");
if(ptr==NULL){printf("Error in oppening file aborting .......");exit(0);}
char ch[100];
scanf("%s",ch);
fprintf(ptr,"%s",ch);
fclose(ptr);
return 0;
}

最佳答案

来自fopen documentation ,支持的访问模式有:

"r" read: Open file for input operations. The file must exist.

"w" write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.

"a" append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist. "r+" read/update: Open a file for update (both for input and output). The file must exist.

"w+" write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.

"a+" append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

在您的代码中,您使用了无效的“rw”,这就是您的程序无法运行的原因。

将“rw”更改为“w”,您的程序就可以运行了。请注意,您不需要创建 output.txt,如果您当前的用户在程序目录中具有写入权限,fopen 将为您创建它。

关于c - C 中的 fprintf() 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com