Thread: Reading from File

  1. #1
    Registered User
    Join Date
    Oct 2004
    Posts
    13

    Question Reading from File

    I am wondering how I am to read in data from a file when there is more then one line in the file.

    For example, I want to read in;

    greg
    stan
    kyle
    mark
    mike

    I am able to read in the first line of data no problem, I am just unsure how to read in the rest.

    Thanks.

  2. #2
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    ...
    
    char line[256];
    FILE *fp = fopen("file.txt", "r");
    
    while (fgets(line, 256, fp) != 0) {
        printf("%s", line);
    }

  3. #3
    Registered User
    Join Date
    Oct 2004
    Posts
    13
    Once I have read the data into the program how would I go about counting the number of certain letters within the string?

    Such as;

    I read in the list;

    greg
    stan
    kyle
    mark
    mike

    and I want to know how many g's are in the first line.

    Thanks.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    How about a loop?

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    </life>
    Join Date
    Oct 2004
    Posts
    83
    Strings are character arrays, the end of a string is marked by the '\0' character.

    Go through each character in the array, if its the one your counting incriment an integer.
    Microsoft is merely an illusion, albeit a very persistant one.

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 the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 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