简体   繁体   中英

How to print out specific lines of user input to console (C++)

I am using c++ and the terminal. So my program takes in user input using read(STD_FILENO,buf,BUFFER and I am trying to write back only specific lines.

So for example, if the user entered in a total of 10 lines, how would I print out lines 3 through 7 or 6 through 10?

I am trying to use the write() function ( write(STD_FILENO,buf,BUFFER) ) but it's not printing what I want it to.
I have tried messing around with the BUFFER and tried to make it smaller than the total amount of characters that the user has input, but it is still not working.

My understanding is that whatever I say the BUFFER is to be, it will write UP TO that BUFFER value, so it will start from 0 to BUFFER. But if I wanted to start from line 6, that may start on character #15 and not 0...does this make sense?

please note: I need to use read() and write()

Thank You!

If you are required to only use read(2) and write(2) , then you'll also need open(2) , close(2) , lseek(2) and you need to design and code your own buffered IO library above it. Read carefully the documentation of every system call mentioned here. Use the result of each of them. Handle error cases in your code. See errno(3) & perror(3) .

So keep a buffer (or more than one) and several pointers (or offsets) into it (probably at least the currently consumed position, and the last read position, etc).

Perhaps you'll want to use some container . You might start implementing your own equivalent of fgetc on your buffered IO class, and build above that.

Lines do not really exist at the system call level. You need to take care of \\n in your code.

BTW you could study, for inspiration, the source code of several free software C libraries implementing <stdio.h> , such as musl-libc

Of course you should compile with all warnings and debug info ( g++ -Wall -Wextra -g with GCC ) and you'll need to use the debugger gdb to understand the behavior of your program and find your bugs. Don't be shy in drawing on some board what happens in your virtual address space (with pointers represented by arrows).

NB: SO is not a do-my-homework service.

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