Jump to content

I have a HW assignment in a class that wants to read/write using low level I/O.

 

Using c's read() and write() calls.

 

The program is meant to concat files, essentially, like so:
 

./prog <file1.in> <file2.in> [file.out]

where file.out is optional, if not specified it prints to stdout. 

 

Anyway, I have written the read/write loops, and they work.

Next up is the extra credit that I want to try.

 

The extra credit is calling for reading in alternating lines from the files, like so:

file1 line1

file2 line1

file1 line2

file2 line2

file1 line3

file2 line3

... etc

 

 

My question is, how could I get the lines alternating? 

 

My code is like so:

 

  while ((ch = read(stdinfd, buf, BUFSZ)) > 0) {
    if (write(fdout, buf, ch) != ch) {
      perror("Write error on stdout\n");
      exit(-1);
    }
    while ((ch = read(stdinfd1, buf, BUFSZ)) > 0) {
      if(write(fdout, buf, ch) != ch) {
        perror("Write error on fdout\n");
        exit(-1);
      }
 
Any help would be awesome
 
Link to comment
https://linustechtips.com/topic/323919-low-level-readwrite-in-c/
Share on other sites

Link to post
Share on other sites

a simple way is to just read a character at a time, and when you find a line break you start copying from the other file

I definitely thought of that. I'm not sure my professor wants that. That's not a low-level I/O function right? Whereas the read() and write() are

Link to comment
https://linustechtips.com/topic/323919-low-level-readwrite-in-c/#findComment-4401719
Share on other sites

Link to post
Share on other sites

I definitely thought of that. I'm not sure my professor wants that. That's not a low-level I/O function right? Whereas the read() and write() are

you can read a character using read() with a buffer of size 1

edit: if you are talking about fgetc(), i wouldn't consider it to be higher level than read() and write(), but i don't know those functions deeply and it might depend on your professor's taste

Link to comment
https://linustechtips.com/topic/323919-low-level-readwrite-in-c/#findComment-4401736
Share on other sites

Link to post
Share on other sites

yeah. I guess I'll have to clarify with him if we can use fgetc()

now that i read the man page for it, i think that fgetc falls into a "higher level" category because it works with FILE*

you could just do this

char ghetto_fgetc(int fd){      char c;      read(fd, &c, 1);      return c;}
Link to comment
https://linustechtips.com/topic/323919-low-level-readwrite-in-c/#findComment-4401858
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×