写工作正常,但读失败-C
下面的代码从另一个模块获取文件路径,打开文件并读取内容。文件正在打开,但读取失败,错误为:文件号错误。然后我在打开后插入了一个写命令,它可以工作,但读取仍然失败。有人能告诉我为什么读取不能工作吗?此外,我还不明白为什么write()在仅用R_模式打开文件时还能工作写工作正常,但读失败-C,c,file-io,C,File Io,下面的代码从另一个模块获取文件路径,打开文件并读取内容。文件正在打开,但读取失败,错误为:文件号错误。然后我在打开后插入了一个写命令,它可以工作,但读取仍然失败。有人能告诉我为什么读取不能工作吗?此外,我还不明白为什么write()在仅用R_模式打开文件时还能工作 char* file_content = (char*) malloc (1024); int fd = open(filepath,"O_RDONLY"); printf(
char* file_content = (char*) malloc (1024);
int fd = open(filepath,"O_RDONLY");
printf("I have attempted open file \n");
fflush(stdout);
bzero(file_content, 1024*sizeof(char));
if(fd <= 0) { //open failed
file_content = "Error opening file";
printf("The error number is %d\n", errno);
fflush(stdout);
}
else
{
if(write(fd, "hello", 5)<0){
printf("write failed");
fflush(stdout);
}
if(read(fd, file_content,1023) < 0){
printf("Error! Read file as %d\n",errno);
fflush(stdout);
}
}
char*文件内容=(char*)malloc(1024);
int fd=open(文件路径,“orduonly”);
printf(“我试图打开文件\n”);
fflush(stdout);
bzero(文件内容,1024*sizeof(char));
如果(fd问题是
open(filepath,"O_RDONLY");
应该是
open(filepath, O_RDONLY);
目前,它使用字符串文本的地址作为打开标志的整数。open(filepath,“ordonly”);
-您最需要阅读open()
(char*)malloc(1024)的手册页
-你最需要了解的是多余的强制转换的有害性质。它一开始是如何编译的?!@JustSid没有理由它不会编译。它会在寻找打开标志时使用字符串的地址作为int
。c非常“宽容”@H2CO3我修复了它。谢谢