gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:24:32 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com