如何解决在 C 中,write() 返回错误的文件描述符错误
我正在编写一个程序,该程序将文件作为命令行参数,然后计算文件中单词/标记的数量。它应该以只读方式打开文件,如果它不存在,则创建它。我已经尝试了各种解决方案,但是一旦到达 write() 调用,我就会继续收到“错误的文件描述符”错误。我刚开始使用这些系统调用,所以我不确定我在哪里犯了错误。
#include<stdlib.h>
#include<stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
char* get_token(int fd);
int main(int argv,char* argc[]){
int fd = open(argc[1],O_RDONLY | O_CREAT);
if(fd == -1){
perror("Open error");
return(EXIT_FAILURE);
}
int count = 0;
char* next_token = get_token(fd);
int write_return = 1;
while(next_token != NULL){
int char_count = 0;
while(next_token[count] != '\n'){
write_return = write(fd,&next_token[char_count],1);
if(write_return == -1){
perror("Writing failure");
return(EXIT_FAILURE);
}
char_count++;
}
if(next_token[count] == '\n'){
write_return = write(fd,1);
if(write_return == -1){
perror("Writing failure");
return(EXIT_FAILURE);
}
}
count++;
}
close(fd);
printf("%d\n",count);
}
get_tokens 函数遍历每个单词,使用 read() 将每个字符添加到缓冲区,直到它到达空格。然后它返回缓冲区。
char* get_token(int fd){
int size = 50;
char* buffer = (char*) malloc(size);
int count = 0;
int read_return = read(fd,&buffer[count],1);
if(read_return == -1){
perror("Reading error");
exit(EXIT_FAILURE);
}
while(buffer[count] != ' ' && buffer[count] != '\t' && buffer[count] != '\n'){
count++;
read_return = read(fd,1);
if(read_return == -1){
perror("Reading error");
exit(EXIT_FAILURE);
}
if(count == size-2){
size += 10;
buffer = (char*) realloc(buffer,size);
}
}
buffer[count] = '\n';
return buffer;
}
我会很感激我能得到的任何帮助。谢谢。
解决方法
如果您以只读模式打开文件,则无法写入文件。这是一个错误的文件描述符。如果要写入文件,请打开 O_RDWR。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。