Thread: Question About Reading Files

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    69

    Question Question About Reading Files

    Hello,

    I'm trying to take files as command line arguments that have one string on each line. Then, I want to put each line into an array of strings. Here is my code:

    Code:
     #include <stdio.h>
     #include <string.h>
     
     main(int argc, char *argv[]) {
        char buf[BUFSIZ];
        char *sorted[BUFSIZ];
        char *tok;
        int stringNum;
        int i;
        FILE *fp;
        
        if (argc > 10) {
           fprintf(stderr, "%s: Too many command line arguments!\n",argv[0]);
           exit(1);
        }
    
        fp = fopen(argv[1],"r");
        while ( fgets(buf, BUFSIZ, fp) ) {
           sorted[stringNum] = buf;
           stringNum++;
        }
        
         printf("%s", sorted[0]);
     }
    I don't know what's wrong with this, but for some reason, it seems to be filling up the array with just the last line in the file. I'm not really familiar with opening and using files.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    What value do you think stringNum holds when you first use it here:
    sorted[stringNum] = buf;


    This:
    >>char buf[BUFSIZ];
    is a single char array, enough to hold one string.

    This
    >>char *sorted[BUFSIZ];
    Is an array of char pointers. Being only pointers, this array doesn't hold any strings, only pointers to strings.

    These two things mean this is incorrect for your use:
    >>sorted[stringNum] = buf;
    What you are actually doing is stoing the location of buf within each pointer in the sorted array. This means they'll all point to the same place.

    A quick fix:
    Use:
    >>#define MAX_LINES 1000 /* or whatever sie */
    >>char sorted[MAX_LINES][BUFSIZ];
    ...
    >>strcpy (sorted[stringNum], buf);
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbish Question file reading question....
    By kas2002 in forum C Programming
    Replies: 23
    Last Post: 05-17-2007, 12:06 PM
  2. Question about IOStream and reading strings from files
    By kingpinzs in forum C++ Programming
    Replies: 22
    Last Post: 12-13-2005, 11:29 AM
  3. reading files
    By hiya in forum C++ Programming
    Replies: 7
    Last Post: 05-21-2005, 11:40 AM
  4. Reading files in a directory
    By roktsyntst in forum Windows Programming
    Replies: 5
    Last Post: 02-07-2003, 10:04 AM
  5. problem reading files in C
    By angelfly in forum C Programming
    Replies: 9
    Last Post: 10-10-2001, 11:58 AM