在C.编译错误中读取文件

0 c

下面的代码无法编译.在我的视觉工作室中STDOUT_FILENO下面有一条卷曲的线条,并没有提供任何关于如何纠正它的建议.

#include <stdio.h>
#include <stdlib.h>
#include "read_file.h"

void main()
{
   char ch, file_name[25];
   //FILE *fp;
   FILE *fd;
   int num_read;

   printf("Enter the name of file you wish to see\n");
   gets(file_name);

   fd = fopen(file_name, "O_RDONLY");
   if (fd < 0)
     {
           perror("Error while opening the file.\n");

       exit(EXIT_FAILURE);
     }
   printf("The contents of %s file are :\n", file_name);

   for (;;)
     {
           num_read = fread(fd, ch, sizeof(ch));
           if (num_read < '0')
             {
               perror("Error while reading the file.\n");
               exit(EXIT_FAILURE);
             }
           if (num_read == 0)
             {
               break;
             }
               fwrite(STDOUT_FILENO, ch, sizeof(ch));
     }

}
Run Code Online (Sandbox Code Playgroud)

Den*_*eng 5

STDOUT_FILENO是定义的unistd.h,所以你需要

#include <unistd.h>
Run Code Online (Sandbox Code Playgroud)

与其他人一起在顶部#include.

编辑:请注意unistd.h,并且扩展STDOUT_FILENO是POSIX标准的一部分,适用于Unix系统.鉴于您使用的是Visual Studio,我假设您正在运行Windows,因此无法在该计算机上使用POSIX内容.


话虽这么说,实际问题可能是你在该行传递的参数看起来不像它们fwrite,它们看起来像是参数write,也是在中定义的unistd.h.

在我看来,你原来的问题是使用像open,read和我这样的函数,write我相信它们都是POSIX(因此无法在Windows上完成).然后,当你有编译问题,你试图取代他们fopen,freadfwrite不改变的参数来匹配新的功能.

正如评论中所提到的,如果你想使用fopen,, freadfwrite(可以在Windows上使用并包含在内stdio.h),请务必正确使用它们.