在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, &next_token[char_count], 1);
if(write_return == -1){
perror("Writing failure");
return(EXIT_FAILURE);
}
}
count++;
}
close(fd);
printf("%dn", 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, &buffer[count], 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。

相关内容

最新更新