Thread: Reading a file from command line

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    5

    Reading a file from command line

    Hi guys,

    I recently have an assignment which will read a file from command line.

    e.g. myprogram < input

    1.) Would like to clarify that the way to read the inputs of the file would be to use fgets()? I have also tried using fscanf, and am not sure on which to go with. I have also searched through this forum and found sscanf, again, not sure on which one to use.

    2.) A second problem I have encountered is that I have no idea on how to "break" the input up into how I want them to be.

    The contents of the input file is a mixture of alphabets and numbers.

    My understanding of fgets() is that it would read the whole line as a string right? So, for example the line read is " c918 = a1203 ". Could you point me in the right direction as to how I would convert that string "c918 = a1203" to an integer -> 918, and hex -> a1203.

    Thanks guys, appreciate the help

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Most likely you will use a combination of fgets to read a line from stdin, then sscanf to get the data into the variables required.

    fgets reads the entire line as a string, yes. It also leaves the newline in the buffer, so you should remove it like so:

    Code:
    char buffer[1024]; // This needs to be large enough to fit the largest line you'll read
    if (fgets(buffer, sizeof(buffer), stdin) != NULL)
    {
        // Remove the newline
        buffer[strlen(buffer) - 1] = 0;
    }
    As I stated above, use sscanf to get formatted input into variables. Google for sscanf and read the docs well.

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    5
    Thanks mate, appreciate your help!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

Tags for this Thread