c - 为什么 (while .. getchar()) 不会在 C 中写入我的文件?
问题描述
我需要编写一个程序,要求用户输入字符串,每个字符串在用户按下“Enter”时结束。
- 程序需要接收文件名作为参数,文件应该为每个操作打开和关闭,对于每个输入的字符串,程序应该将字符串附加到文件的末尾(在新行上)。
到目前为止,这是我的代码:
int is_file_exists(char *file_name)
{
FILE *file;
if ((file = fopen(file_name,"r"))!=NULL)
{
/* file exists */
fclose(file);
return 1;
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
return 0;
}
}
int main(int argc, char **argv)
{
char c;
FILE *file;
if (argc >= 2)
{
if (is_file_exists(argv[1]))
{
file = fopen(argv[1], "w");
}
else
{
return 0;
}
}
else
{
file = fopen("file.txt", "w");
}
while ((c = getchar()) != EOF)
{
putc(c, file);
}
return 0;
}
到目前为止,代码已编译并正在创建文件,但其中没有写入任何内容。
编辑:我还需要一些函数指针,请参阅我对选定答案的评论
解决方案
我认为问题之一是您正在打开和关闭文件,然后随后重新打开它。最好使用指针将其保持打开状态,同时测试打开文件是否没有问题。另一个问题是您在文件中写入,您不喜欢将文本附加到它吗?好吧,这是你的决定。至于代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // exit
typedef struct mystruct {
char *exit_word;
void (*exit_fptr)(int); // man exit
int (*strcmp_fptr)(const char *, const char*); // man strcmp
} t_mystruct;
int is_file_exists(char *filename, FILE **file)
{
return (*file = fopen(filename,"a")) > 0;
}
#define BUFF_SIZE 1024
int main(int argc, char **argv)
{
char c;
FILE *file;
t_mystruct s = {.exit_word = "-exit", .exit_fptr = &exit, .strcmp_fptr = &strcmp};
if (argc >= 2) {
if (!(is_file_exists(argv[1], &file)))
return 0;
}
else
file = fopen("file.txt", "a"); // open the file in append mode
char buffer[BUFF_SIZE];
while (42) {
int i = 0;
memset(buffer, 0, BUFF_SIZE);
while ((c = getchar()) != '\n')
buffer[i++] = c;
if (!s.strcmp_fptr(buffer,s.exit_word)) {// exit if user type exit, allow you to fclose the file
fclose(file);
s.exit_fptr(EXIT_SUCCESS); // better to use the define
}
buffer[i] = '\n';
fputs(buffer, file);
}
fclose(file);
return 0;
}
推荐阅读
- postgresql - 减去一天Postgresql
- python - 如何使用最大似然估计将负二项模型拟合到数据中
- java - 登录认证后spring boot jwt没有重定向
- python - 如何在不更改代码的情况下从任意位置导入 Python 文件?
- c++ - 当客户端数据的步幅较小时上传到统一缓冲区对象
- python - 为什么在某些训练迭代中训练集的准确率会下降?
- ios - 在 Sprite 套件中未检测到联系人
- github - 在 github 工作流中使用 PR 作者的名字作为环境
- cakephp - 在 CakePHP 中使用 TreeBehavior 从文本中保存新树
- mysql - 每天晚上被删除的表上的 Mysql 索引