unbuffered I/O: read int from file and write it on standard output

765 Views Asked by At

This program is meant to take as parameter a file, then read a string from standard input and write its length into the file, then read the content of the file (which is supposed to contain the lengths of the strings from the standard input) and write it in standard output:

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

#define MAX_BUFF 4096

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        puts("you must specify a file!");
    return -1;
    }
    int nRead;
    char buffer[MAX_BUFF], tmp;
    int fd;
        puts("write \"end\" to stop:");
    fd = open(argv[1], O_RDWR | O_CREAT | O_APPEND, S_IRWXU);
    while ((nRead = read(STDIN_FILENO, buffer, MAX_BUFF)) > 0 && strncmp(buffer,"end", nRead-1) != 0 )
            {
            if ( write(fd, &nRead, 1) < 0 )
            {
                perror("write error.");
                return -1;
            }
        }
    puts("now i am gonna print the length of the strings:");
    lseek(fd, 0, SEEK_SET); //set the offset at start of the file
        while ((nRead = read(fd, buffer, 1)) > 0)
    {
        tmp = (char)buffer[0];
        write(STDOUT_FILENO, &tmp, 1);
    }
    close(fd);
    return 0;
}

this is the result:

write "end" to stop:
hello
world
i am a script
end
now i am gonna print the length of the strings:

I tried to convert the values written in the file into char before write in standard output with no success. How am i supposed to print on standard output the lengths by using unbuffered I/O? Thank you for your replies

EDIT: i changed the read from file with this:

while((read(fd, &buffer, 1)) > 0)
          {
                  tmp = (int)*buffer;
                  sprintf(buffer,"%d:", tmp);
                  read(fd, &buffer[strlen(buffer)], tmp);
                  write(STDOUT_FILENO, buffer, strlen(buffer));
          }

but actually i have no control on the effective strlen of the string thus the output is this:

13:ciao atottti
4:wow
o atottti
5:fine
 atottti

as you can see, the strlength is correct because it consinder the newline character ttoo. Still there is no control on the effective buffer size.

0

There are 0 best solutions below