How Can You Redirect scanf to Read from a File in GCC?

  • Thread starter Thread starter Werg22
  • Start date Start date
  • Tags Tags
    Gcc
AI Thread Summary
To modify a program that uses scanf for user input to read from a text file, the recommended approach is to use fopen() to open the file and then utilize fscanf() for reading data. For command line usage, input redirection can be achieved using the "<" symbol, allowing the program to read from a file directly. For writing test cases that involve file input, the discussion suggests using assert statements, but highlights the challenge of adapting this method for file reading. A potential solution is to open a file within the test framework, enabling scanf to read from it. The conversation emphasizes the need for clarity on how to integrate file reading into testing scenarios.
Werg22
Messages
1,431
Reaction score
1
I have a code which uses scanf. How do I make the compiled code read from a (text) file instead from user's input?
 
Technology news on Phys.org
open the file with fopen() and then use fscanf()
if you search for these terms you should find lots of examples
 
That's an idea, but I need to be able to do it from the command line... I know there's a way, involving the symbol "<", I just don't remember the details.
 
If you just want the same code to read from a file you can just use:
program << file.txt
 
Thank you very much. Maybe you can answer this question too: how can I write test cases for my program, keeping in mind it has to read from files? I'm used to using "assert" for tests, by copying my program into a header file and then writing a main function with a bunch of assert statements. In this case, I can't exactly use assert. Is there a statement that opens a file and let's scanf read from it?
 
Did you read the second post?
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top