出于好奇,我有下面的代码(不是我的)试图让它工作。 从这里C low-level standard-in to accept filename then printing file contents to stdout
int checkfile(void)
{
char buffer[4096];
char userInput[100];
int input_file1;
int n;
/* Check file existence. */
printf("Enter the filename: \n");
fflush(NULL);
if (!fgets(userInput,sizeof(userInput),stdin))
{
perror("fgets");
exit(EXIT_FAILURE); };
if((input_file1 = open(userInput, O_RDONLY)) < 0)
{
perror(userInput);
exit(1);
}
while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
{
if((write(STDOUT_FILENO, buffer, n)) < 0)
{
perror("failed to display file to output");
close(input_file1);
exit(1);
}
}
}
每当我运行代码并尝试打开名为“success.txt”的文件时,我都会遇到段错误
"RUN FINISHED; Segmentation fault; core dumped; real time: 3s; user: 0ms; system: 0ms"
我也在我的主代码中调用它作为
checkfile();
如果这有什么不同。
有人可以向我指出我所缺少的东西吗,因为我现在看不到它。我感觉我的一些变量设置不正确...但不确定,谢谢。
最佳答案
if (!fgets(userInput,sizeof(userInput),stdin))
有几个帐户是错误的。
userInput
没有指向任何有效内存。sizeof(userInput)
和sizeof(char*)
是一样的,不是你想要的。
改变
char *userInput;
类似于:
char userInput[100];
下一个问题
if((input_file1 = open(userInput, O_RDONLY)) < 0)
这是错误的。 open
的返回值是一个int
。 input_file1
的类型是 FILE*
。我很惊讶您没有收到编译器错误/警告。
改变
FILE *input_file1;
到
int input_file1;
下一个问题
这可能是由于 fgets()
在 userInput
中包含换行符引起的。添加代码以修剪换行符。
int len = strlen(userInput);
if ( userInput[len-1] == '\n' )
{
userInput[len-1] = '\0';
}
关于无法使用读/fgets/写到 C 中的标准输出来显示文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29454641/