在 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。