0
votes

So I have to implement a program that works with a text file (.txt), which has been put to stdin like that: ./program [argumets] <textfile.txt without using such functions as fopen, fscanf, malloc, etc. and I have no idea how to do that. I need to work with characters in that text file (print them to screen, print max/min value, print sum, etc.), NOT with the file itself, so, maybe anyone got a hint? Thank you.

1
the basic file handling function will help you.. open() - Haris
You don't have to do anything special to get from stdin. It's automatically opened for you, you can just read from it. - Barmar
You have to remember that stdin is a normal file stream just as the ones opened by fopen. Start by trying to use e.g. fscanf or similar functions with stdin and you can then easily switch that out to a file opened by fopen instead. - Some programmer dude

1 Answers

0
votes

Reading from text file like this as nearly identical to reading from keyboard. So much so that without doing some special tricks, your program has no way to know if input comes from keyboarad or from file.

When you do need to use a function which requires a file, there is stdin, which is so called "file pointer", and has type FILE*, same as returned by fopen. File pointer is accepted by functions likes fscanf (but you can just call scanf then) and fgets (do NOT use gets, it's fatally broken, and finally removed from C11 standard).

If you need to use functions which take file descriptor, which is integer, and returned for example by open call, and accepted by functions like read, then the file descriptor number for standard input is 0, but you should usually use the STDIN_FILENO constant. And, do not mix reading from file descriptor (unbuffered), and reading from FILE* (buffered), because buffering will mess up the data you get. Using FILE* is probably better for most applications.

To make this more concrete, you can develop your program so, that instead of using < to redirect the input file, you can open the input file in editor, copy it to clipboard, run your application in a terminal, and paste input file as text to the terminal.