c - 简单的Linux编程: File read not going well?

标签 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);
}

最佳答案

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

这被解析为:

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

将 0 或 1 分配给 fd。你需要一组额外的括号:

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

或者更好的是,将其写成两行。

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

关于c - 简单的Linux编程: File read not going well?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13405152/

相关文章:

c - 如何在 C 中以正确的方式从二进制结构中打印位域?

c - 任意长度的随机数生成器

xml - 在 shell 脚本中需要帮助以查找和替换 xml 文件中的值

c++ - ofStream 错误 : writing to text file?

C# 使用其他域/用户名/密码将文件复制到另一个目录

python - 使用Python读取文件中包含多个单词的字符串

c - 尝试从文件读取行返回不正确的行

c - 我应该在 C 中的 basename/dirname 之后释放 strdup 指针吗?

c++ - 尽管文件存在,但已编译的 C++ 程序在另一个系统上引发 "cannot open shared object file"

linux - epoll 为 timerfd 报告 EPOLLIN 后,read() 返回 EAGAIN