Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file in C with File Descriptor

I want to read from a file by using its file descriptor. I can't use its name because of assignment rules.

I obtain it by calling open and it works fine. At this moment I know that I have to use the read() function in order to read from it. My problem is that read() function requires as an argument the number of bytes to read, and I want to read a whole line from the file each time, so I don't know how many bytes to read.

If i use for example fscanf(), it works fine with a simple string and I take back the whole line as I want. So my question is:

Is there any function like fscanf() which can be called with file descriptor and not with a file pointer?

like image 765
Spyros Avatar asked Nov 17 '25 12:11

Spyros


2 Answers

When you say "have to use read()" I can't tell if that's your understanding of the situation given a file descriptor from open() or a restriction on some kind of assignment.

If you have a file descriptor but you're more comfortable with fscanf() and friends, use fdopen() to get a FILE * from your fd and proceed to use stdio.

Internally it uses functions like read() into a buffer and then processes those buffers as you read them with fscanf() and friends.

like image 58
Ben Jackson Avatar answered Nov 20 '25 02:11

Ben Jackson


What you could do is read one character at a time, until you've read the entire line, and detect a '/n'. As this is homework, I won't write it for you.

A few things to be warned of, however.

  1. You need to check for EOF, otherwise, you might end up in an infinite loop.
  2. You should declare some buffer which you read a character, then copy it into the buffer. Not knowing what your input is, I can't suggest a size, other than to say that for a homework assignment, [256] would probably be sufficient.
  3. You need to make sure you don't overfill your buffer in the even that you do run over it's length.
  4. Keep reading until you find a '/n' character. Then process the line that you have created, and start the next one.
like image 40
PearsonArtPhoto Avatar answered Nov 20 '25 03:11

PearsonArtPhoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!