Getting substring of a string from a file.txt read by read system call

Viewed 50

Let's suppose we have a file lista.txt with this content:

John abc
Mark cdf
Susie hhh

how can I get the first words of each row? (John and Mark and Susie)?

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#define BUF_DIM 1000

struct elem{
    char nome[BUF_DIM];
};


int main() 
{
    int fileDescriptor;
    int nread;
    char carattere;
    char nickname[BUF_DIM];
    int i = 0, times = 0;

    struct elem *top = NULL;

    // Apertura del file in sola lettura
    if( (fileDescriptor=open("lista.txt", O_RDONLY)) == -1 ){
        perror("Errore con apertura del file");
        exit(1);
    }

    // Lettura del file
    while( read(fileDescriptor, &carattere, 1) == 1){ // un byte alla volta
        if (carattere != ' ') {
            times++;
            //printf("%c\n", carattere);
            nickname[i++] = carattere;
            //printf("%c\n", nickname[i++])
        }
        else {
            nickname[i++] = ' ';
        }
    }

    nickname[times] = '\0';

    printf("%s\n", nickname);


    close(fileDescriptor);

    return 0;
}
2 Answers

In order to find the first word in each line, you first need to split to lines. at the end of each line there is a special character. you can find it by comparing to \n.

If you need to parse all the words, allocate a buffer that can hold 2 lines and read until you found a \n. Then parse the line you have in the buffer and remove it.

If you need only the first word, i suggest to read until you find a whitespace and then skip until \n.

Using read to read a text file is very cumbersome. It would be much simpler to use the standard stream functions, fopen() / fclose(), fgets() or even fscanf().

If you must use the read system call, I suggest you implement a function that reads a line from the text file reading one byte at a time with read copy the line contents inside the loop.

Note that perror("Errore in lettura"); is inappropriate when you detect a write error.

Related