问题描述
我需要编写一个程序,要求用户输入字符串,每个字符串在用户按下“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,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;
}
,
你的代码可以工作
记得在输入完成后按 Ctrl+d。该文件将包含您期望的内容
您的代码等待 EOF 退出循环。 Ctrl+d 是输入 EOF 的一种方式,否则程序永远不会结束。 putc 将首先写入缓存,然后写入磁盘。这是文件系统的一种优化机制。您可以选择在打开文件时通过 DirectIO 避免这种情况。
当程序正常终止时,文件会自动关闭,然后缓存中的数据会被复制到磁盘;
但是当程序异常终止时,缓存中的数据可能会丢失。
文件应该关闭
需要 fclose。 open 和 close 应该成对组织,就像 malloc 和 free 一样。