简体   繁体   中英

How do i display the first 10 words on my terminal without using stdio.h

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM