Da Mike
Da Mike

Reputation: 463

Reading strings with read() system call in C

I need to implement a C function

ssize_t readString(int filedes, char* buf, ssize_t max);

that reads a string from file associated with file descriptor 'filedes' , into buffer 'buf' and returns the number of bytes read. The 'max' variable isn't necessary.

In other words I want to use

readString(fileDescriptor, buf);

the same way I would use

fscanf(inputFile, "%s", buf);

Below I refer what I have done so far, but it doesn't work well at all times. Do you have any suggestions for my code? Can you suggest a better implementation of this function?

Thanks

ssize_t readString(int filedes, char* buf){
    char *temp;
    int n = sizeof(buf)/sizeof(char); int i;
    ssize_t rbytes = 0; /* bytes read */
    size_t cbyte = sizeof(char);

    /* check if file is empty */
    if (read(filedes, temp, cbyte) < 1)
        return 0;

    /* eat spaces */
    while ( (*temp == ' ') || (*temp == '\n') || (*temp == '\t') )
        if (read(filedes, temp, cbyte) < 1)
            return 0;

    /* read string */
    for (i=0; i<n-1; i++){
        buf[i] = *temp;
        rbytes++;

        /* check if file is over */
        if (read(filedes, temp, cbyte) < 1)
            return rbytes;
        /* check if string is over */
        if ( (*temp == ' ') || (*temp == '\n') || (*temp == '\t') )
            break;
    }

    buf[++i] = '\0';
    return rbytes;
}

Upvotes: 0

Views: 4486

Answers (1)

David Schwartz
David Schwartz

Reputation: 182763

ssize_t readString(int filedes, char* buf){
    char *temp;
    int n = sizeof(buf)/sizeof(char); int i;

I think you misunderstand what sizeof does. It figures out the size of the thing you ask it to figure out the size of. In this case, that's buf, which is a char *. So you're basically asking it how many bytes a pointer to a character takes. Presumably, you want the size of the buffer. So your function needs that as an additional parameter.

Upvotes: 1

Related Questions