c - C 中使用动态字符串的文件 I/O

标签 c string io

<分区>

我正在尝试编写一个执行以下操作的简单程序:

  • 选择一个文件
  • 选择如何处理文件(fopen 模式:r、w、a、r+...)
  • 写入文件

到目前为止,这是我的代码:

//Gets future file content
printf("Write content:\n");
char content[100];
fgets(content, 100, stdin);

//Selects file
printf("Select output file: ");
char file[30];
fgets(file, 30, stdin);

//Selects mode
printf("Select mode: ");
char mode[3];
fgets(mode, 3, stdin);

    FILE *fp;
    fp = fopen(file, mode);

    if (fp == 0) {
       printf("File NOT opened\n");
    }

我希望将变量“file”用作文件的字符串/路径,“mode”变量也是如此。 当我运行程序时,我发现文件没有打开,这意味着 fp 是一个空指针。

PS:这不是完整的代码,但这就是破坏它的原因

提前致谢

最佳答案

添加这一行

fprintf(stderr, "file='%s'\n", file);

在您阅读 file 并了解到如果通过按 Enter 终止输入时将读取换行符。

来自 man fgets() (斜体 由我):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.


根据 Chris Dodd 下面的评论:这同样适用于读入 mode 的字符串。

关于c - C 中使用动态字符串的文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789323/

相关文章:

c - 暴力破解查找 FILE* C

c++ - YCM是否支持完成内置功能?

java - Android java 追加 n 个字符到字符串

c - 为什么指针 "Start"会改变? (C)

php - 如何查找字符串中字符出现的数组

"\0"null 的 Ruby 测试?

java - 当文件确实存在时抛出 FileNotFoundException

python - 在python中将字符串视为文件

c++ - 大量文件的原子删除

c - 我如何知道调制解调器何时完成对 AT 命令的响应?