简单的Linux编程:文件读取不顺利?

时间:2012-11-15 19:57:57

标签: c linux file

我正在尝试编写一个简单的程序来从文件中读取并在终端中打印它。但程序在打开文件后挂起。如果我删除阅读部分,它运作良好。我不知道出了什么问题。有人可以帮忙吗?请!

#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
  int fd,bytes;
  char buffer[10];
  char path[ ] = "file";

  if(fd = open(path, O_RDONLY) < 0) {
    perror("open");
    exit(EXIT_FAILURE);

  } else {
    printf("opened %s\n", path);
  }

  do {
    bytes = read(fd,buffer,10);
    printf("%d", bytes);
  } while( bytes > 0);

  if(close(fd) < 0) {
    perror("close");exit(EXIT_FAILURE);
  } else{
    printf("closed %s\n", path);
  }
  exit(EXIT_SUCCESS);
}

2 个答案:

答案 0 :(得分:4)

if(fd = open(path, O_RDONLY) < 0) {

这被解析为:

if(fd = (open(path, O_RDONLY) < 0)) {

将0或1分配给fd。你需要一套额外的parens:

if((fd = open(path, O_RDONLY)) < 0) {

或者更好,将它写成两行。

fd = open(...);
if (fd < 0) {

答案 1 :(得分:2)

所以,首先你的程序如Mat解释的那样,如果“file”存在则将0分配给fd。连续读取从stdin读取。这可以解释为“悬挂”,但实际上你的程序只是从stdin读取,而你的printf没有显示,因为最后没有\ n。如果将其更改为

do {
  bytes = read(fd,buffer,10);
  printf("%d", bytes);
  fflush (stdout);
} while( bytes > 0);

然后你会看到会发生什么...... 欢呼声。