在 C 中使用系统调用读取和搜索文件

Reading and searching files using systemcalls in C

我尝试从文件 "hello.txt" 中读取,但它根本没有进入 while 循环。读取函数 returns EOF 为 0,错误为 -1。我正在尝试搜索 w 中的单词是否存在于文件中。我正在从文件中读取字符并将它们与 w[].

进行比较
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main()
{

  int fd;
  char c;
  int i=0;
  int bytesread;
  int flag=1;

  char w[]={'h','e','l','l','o'};

  if((fd=open("hello.txt",O_RDONLY,0))!=-1){ //if 1

    bytesread = read(fd,&c,0);

    if(bytesread!=-1){      //if 2

    while(bytesread!=0)
    {                      //while

      if(c==w[i])
      {                   //if 3
        i++;
        flag=0;
      }                  //end of f3

      else if(flag==0&&i!=0)   
      {                  // else 3
        i=0; 
        flag=1;

      }                  // end of else 3

      bytesread = read(fd,&c,0);
    }   //end of while

    }else  //end of if 2
      printf("couldn't read file.\n");

    }else //end of if 1
    printf("Couldn't open file for read.\n");

  } //end of main

read(fd,&c,0)要求系统读取零字节,这不应该是你想做的。

你应该让系统按read(fd,&c,1)读取一个字节。

ssize_t read(int fd, void *buf, size_t count);

read 从文件中读取 count 字节。您要求它在执行 bytesread = read(fd,&c,0); 时读取零字节。将其更改为 bytesread = read(fd,&c,1);

试试这个:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{

    int fd;
    char c;
    int bytesread;

    if ((fd = open("hello.txt", O_RDONLY, 0)) != -1) {

        while ((bytesread = read(fd, &c, 1)) == 1) 
            printf("read %d bytes [%c]\n", bytesread, c);

    } else          
        printf("Couldn't open file for read.\n");

    return 0;
}