Low Level I/O - Read/Creat/Write (C)

MBan picture MBan · Oct 30, 2013 · Viewed 8.4k times · Source

I'm trying to use low level functions in C and wanting to read from the STDIN and store that information in a file.

int dash, c;
char buffer[1024];
if((dash = creat("file.txt", S_IRWXU)) < 0)
    perror("creat error");
while ((c = read(STDIN_FILENO, buffer, sizeof(buffer))) > 0) {
    if (write(dash, buffer, c) != c)
       perror("write error");

I having a problem understanding how I can access 'file.txt' to read it to either print to the screen or store to another file. Would I just use 'read("file.txt", buffer, sizeof[buffer])'?

EDIT Now after creating "file.txt" I want to open another file, lets say file1 (argv[3]) and dump "file.txt" into file1 (agrv[3]). Would this work?

fd = open(argv[3], O_RDWR); //open 3rd arg for writing
fd_2 = open("file.txt", O_RDWR); //open created file
do {
     n = read(fd_2, buffer, sizeof(buffer));
     if (n < 0)
        perror("read error argv[2]"); //greater 0=succesful
     write(STDOUT_FILENO, buffer, n); // this is where I'm stuck
    } while (n == sizeof(buffer));
close(fd);

I have both files open now but can't figure out how to write "file.txt" into argv[3].

Answer

Yu Hao picture Yu Hao · Oct 30, 2013

Use open() to get the file descriptor:

int fd = open("file.txt", O_RDWR);

Then you can use read() to read from this file descriptor just like STDIN_FILENO.

c = read(fd, buffer, sizeof(buffer));

Make sure to check for the return value of both functions in real code.