Thread: Reading text out of a file

  1. #1
    Registered User Twiggy's Avatar
    Join Date
    Oct 2001
    Posts
    43

    Reading text out of a file

    I was wondering how I would go about making up a list of questions and answers in notepad, and then having my program read them and then check the answer out of this one file. I perfected my little true and false quiz using tables. But its a pain if I want to add a new question to have to compile the entire code over again. This way I can just change it in the questions.txt file and be done with it. I know how to write the results of something into the file. Just not sure on how to read from the file, I haven't found a tutorial that explains that part yet.

    Nate

  2. #2
    Unregistered
    Guest
    Here are some real basics. I'm sure someone else could probably elaborate/be more helpful.

    First you need to declare a pointer to a file:

    FILE *in_file;


    then you need to open the file for reading and check to see if it worked:

    in_file = fopen("File name/path goes here", "r");
    if (in_file == (FILE *) NULL)
    {
    printf("Failed to open file.");
    exit(1);
    }

    then you can read each line with something like

    while(fgets(stringname, n, in_file) != NULL){

    **perform what you want to do with each line from the file **

    }

    where "stringname" is the string you want to store the line from the file in and n-1 is the maximum # of characters it will read per line... it will read up to that or until it finds a "\n"

    finally, close the file

    fclose(in_file);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Reading Character at a time from a text file
    By Giania in forum C Programming
    Replies: 8
    Last Post: 02-25-2006, 03:17 PM
  5. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 02:59 PM