Search code examples
cfileoperating-systemposixsystem-calls

Read from a file until a space is found


I'm new to C programming, so I wonder if it's possible to read from a certain file using the system call read() until a space is found.

Example:

A file contains a number and a process PID (59 5542). I want to read first the number, saving it into a variable and then do the same thing with the PID.

Thanks in advance.

P.S: since this is an exercise for my Operating Systems class, I have to use read().


Solution

  • I recommend first reading the number and the PID with one read() call into a sufficiently large buffer, then saving both into variables, e. g.:

        char buf[20] = { 0 }, *end;
        read(fd, buf, sizeof buf - 1);
        int num, PID;
        num = strtol(buf, &end, 0);
        PID = strtol(end, NULL, 0);