🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Getting Standard Input In C Program

Started by
0 comments, last by let_bound 17 years ago
I'm pretty new to making command line tools, but I need one for an email sorting/analyzing program. I found a program that will get the emails and then filter them by sending the data to an application of my choice. I have it sent to my custom application and it works, but it's sending it via the standard input I believe (so something like 'mailChecker < email'). How do I go about reading in this data in my C program without reading too little or too much? Any suggestions or links? I've been Googling, but all I've managed to find are overviews and explanations of the standard input; not necessarily how to use it. Thanks in advance.
Advertisement
Just read stdin like you would any other stream. Here's a (very) minimalist example in C++ that simply echoes everything it read on stdin. It reads until it reaches EOF.

#include <iostream>#include <string>#include <algorithm>int main() {  std::string str;  std::getline(std::cin, str, static_cast<char>(EOF));  std::cout << str << std::endl;}


Sorry for not writing it in C, but I'm too tired to think, and C++ makes it easy here. The basic idea is the same anyway: read the standard input (stdin) until you reach EOF.

EDIT: so I missed that part of your post about not reading too much or too little. Sorry.

In C, you'll want to loop until you reach EOF (see feof(3)), reading a chunk of data in a a buffer. You have multiple options here:

  • use a heap allocated buffer, and use realloc(3) to increase its size when needed,

  • use fixed size, heap allocated buffer, and store them in all a linked list that you'll flatten in the end,

  • use a linked list of characters that you'll flatten in the end,

  • use a stack allocated, fixed-size buffer to read the data into, and then copy it to a heap allocated buffer that you'll resize with realloc(3) when appropriate,
  • ...



Remember to take the return value of fread(3) into account: it's very likely that the last read, at least, will not fill the buffer entirely. Don't assume that the buffer is always full.


[Edited by - let_bound on July 7, 2007 3:55:17 AM]

This topic is closed to new replies.

Advertisement