使用动态字符串在C中进行文件I/O [英] File I/O in C using dynamic strings

查看:126
本文介绍了使用动态字符串在C中进行文件I/O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to code a simple program that does the following:

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

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

this is my code so far:

//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");
    }

我希望将变量文件"用作文件的字符串/路径,模式"变量也是如此. 当我运行程序时,我得到的是文件未打开,这意味着fp是空指针.

I want the variable "file" to be used as the string/path to the file, and same goes for the "mode" variable. When I run the program I get that the file is not opened, meaning that fp is a null pointer.

PS:并不是全部代码,但这就是要破坏的代码

PS: It is not the whole code, but that's what's breaking it

预先感谢

推荐答案

添加此行

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

在阅读file之后,如果按 Enter 终止了输入,则得知将读取换行符.

after you read file and learn that a newline is read if the input was terminated by hitting Enter.

来自 man fgets() (斜体字):

fgets()从流中读取最多小于大小的字符,并将其存储到s所指向的缓冲区中.在EOF或换行符之后停止读取. 如果读取换行符,则将其存储到 缓冲区.终止的空字节(\\ 0)存储在缓冲区中的最后一个字符之后.

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的字符串也是如此.


As per Chris Dodd's comment below: The same applies to the string read into mode.

这篇关于使用动态字符串在C中进行文件I/O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆