Hey how'd i be able to output the first 10 words of the text file without using stdio.h
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd_to_read = open("sample.txt", O_RDONLY);
if(fd_to_read == -1){
exit(1);
}
close(fd_to_read);
}
//I've no idea how i'm able to display the first 10 words without the use of stdio.h
CodePudding user response:
On POSIX systems the io primitives are: open, close, read, write.
These primitives operate on file descriptors rather than an FILE object as purposed by the C Standard.
Like the c io interface, the posix interface expects a buffer and a buffer size for the read and write primitives.
Assuming that words are separated by the whitespace character ' ', your job would be to read continuously from the source descriptor and count the occurrences of the space character (by iterating over the buffer char by char) until it hits the desired threshold.
Until then, write everything to the output descriptor.
In <unistd.h>
you'll find these three importatnt symbols:
- STDIN_FILENO
- STDOUT_FILENO
- STDERR_FILENO
CodePudding user response:
This problem is more difficult than it looks: you cannot use <stdio.h>
so you must use system calls to read from the file and write to stdout
:
Read a byte:
char ch; if (read(0, &ch, 1) != 1) { /* end of file reached */ break; }
Write the byte to
stdout
:write(0, &ch, 1);
Testing for word boundaries is more tricky: you must skip all white space, then you have a new word until you read more white space.