无法使用读/fgets/写到 C 中的标准输出来显示文件

标签 c

出于好奇,我有下面的代码(不是我的)试图让它工作。 从这里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))

有几个帐户是错误的。

  1. userInput 没有指向任何有效内存。
  2. sizeof(userInput)sizeof(char*)是一样的,不是你想要的。

改变

char *userInput;

类似于:

char userInput[100];

下一个问题

if((input_file1 = open(userInput, O_RDONLY)) < 0)

这是错误的。 open 的返回值是一个intinput_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/

相关文章:

c - 为什么在 typedef 中使用指针?

c - 如何在 C 中打印 .10 而不是 .1?

c - 跟踪指针

c - C中数组中的关键字

c - openmp 排序临界区

我根本找不到C内存泄漏

c - 如何在 C 语言中逐个字母地打印用户输入的内容?

c - 如何创建 C 宏来定义函数 typedef?

c - 信号处理程序中的 pgid 与真实 pgid 不同

c - 查询有关通过 valgrind 运行程序并与其他系统相比得到错误结果的问题