Thread: problem reading a text file.

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    77

    problem reading a text file.

    I am trying to write a program to read a text file. The text file has the following format:

    filename section varname1 varname2 varname3 ... varname(n)

    There can be multiple lines of this line. The filename, section, and varnames can be of varying length.

    Here is an example of the text file that I need to read.

    lions.txt sec_2.5-1 height weight color gender
    zebras.txt sec_12.11-22 speed height gender coloration markings location

    Here is my code:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        //**********************************
        // Open "animals.txt" input file
       //**********************************
       // animal data
        FILE *f;
        char s[500], a1[20], a2[20], a3[20], a4[20];
    	char file_name[10][10], ch [10[10];
    
        f=fopen("file_list.txt","r");
        if (!f)
            return 1;
        while (fgets(s,sizeof(s),f)!=NULL)  //while not EOF
    		// scan one line at a time
            sscanf (s, "%s %s %s %s",a1,a2,a3,a4);
    	    strncpy (ch[i], a1, 9);
    	    file_name[i][1] = ch[i][1];
    		printf("file_name  = %s\n",file_name[i][1]) ;
    
            printf("%s\n",s);
        fclose(f);
        return 0;
    
    }
    The problem that I can't seem to solve is that the filename is not getting copied into the variable "ch[i]".

    Thanks in advance for any help!
    Last edited by jerrykelleyjr; 10-24-2006 at 07:36 AM. Reason: Fixed [code][/code] tags.

  2. #2
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Look at your code again your while loop doesn't have opening braces and a closing braces

    ssharish2005

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    77
    oops I forgot to cut and paste them.

    They are not the problem with the filename not getting copied into the ch and file_name variables correctly. When I run the code in the debugger and run to the line after the strncpy line the "a1" variable has the filename in it but the ch[i] variable has some hex value and not the filename. Any ideas? Thanks again!
    Last edited by jerrykelleyjr; 10-23-2006 at 05:18 PM.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    1. Why is this declared as a two dimensional array?
    char file_name[10][10];

    2. Why aren't you treating it like one at this line?
    strncpy (file_name[i], a1, 9);

    Maybe that's why nothing is being copied.

    3. Where is ch defined? Or am I blind?
    file_name[i][1] = ch[i][1];

    4. Are you aware that arrays start at zero in C?

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    77
    The array is two dimensional because I need to read multiple lines of text.

    The ch var is declared I forgot to cut and paste it. I apologize about the bad cut and paste job!

    Yes, I know arrays start at zero in C.

    Having said this, what is the problem with my code?

    Thanks again!

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The strncpy line is wrong.

    If you declare an array as having two dimensions you're pretty much stuck using the form
    array[column][row]
    unless you use some pointer math.

    And...
    file_name[i][1] = ch[i][1];
    assigns one character, and doesn't copy the whole string. What's even stranger is that you take all this time to try to fill ch[][] and never use it for much.

  7. #7
    Registered User
    Join Date
    Dec 2004
    Posts
    77
    what would you do instead? Remember I need to read multiple lines of text. Therefore the filename appears on each line as the first word. How can I accomplish what I want to do? I'm not professing this code is elegant...that I know it is not. I just need some help. Thanks !

  8. #8
    Registered User
    Join Date
    Dec 2004
    Posts
    77
    OK let me restate what I need to do.

    Please refer to the original post. I nee dto read lines of test from a text file. Each line contains a filename, section, and variable names.

    My question is this. What is the best way to read lines of text and store each word on each line for later use? I really appreciate any help!
    Thanks in advance!

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > ch [10[10];
    How about posting some code which
    a) compiles
    b) has braces in all the places which you've neglected to mention.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Dec 2004
    Posts
    77
    OK Salem. I need to read from a text file the following:

    filename section var1 var2 ...var(n)
    filename section var1 var2 ...var(n)
    .
    .
    filename section var1 var2 ...var(n)


    Note: some lines only have 1 var some have up to 20 var's.
    I need to store this filename, section, and var text into variables.
    My question is this. How can this best be accomplished?

    My code is obviously incomplete but I don't know how to get all of the data into variables. Plus I don't know how to make it flexible so that it will handle lines with only 1 var or lines with up to 20 var's. Thanks for your help!

    Here is my code thus far:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        FILE *f;
        char s[500], a1[15], a2[10], a3[10], a4[10];
    	char file_name[10];
    	int i=0;
    
        f=fopen("filedata.txt","r");
        if (!f)
            return 1;
        while (fgets(s,sizeof(s),f)!=NULL)  //while not EOF
    	{
    		// scan one line at a time
            sscanf (s, "%s %s %s %s",a1,a2,a3,a4);
    	    strncpy (file_name, a1, 15);
    	    printf("file_name  = %s\n",file_name) ;
    
        fclose(f);
    	}
        return 0;
    
    }
    Last edited by Salem; 10-24-2006 at 10:17 AM. Reason: Put the code tags AROUND the code, not just in the message to make it stfu

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    What type are vars? ints, doubles, strings?

    Assuming all strings, and up to 20 of them, try
    Code:
    char filename[10], section[10], vars[20][10];
    while (fgets(s,sizeof(s),f)!=NULL) ) {
      int r, n;
      char *p = s;
      int i = 0;
      r = sscanf( p, "%s %s%n", filename, section, &n );
      if ( r == 2 ) {
        p += n; /* advance by the number of chars processed */
        while ( i < 20 && sscanf( p, "%s%n", vars[i], &n) == 1 ) {
          p += n;
          i++;
        }
      }
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Dec 2004
    Posts
    77
    Salem Thanks! I mean it.

    All text is characters.

    Another question. How can I check for duplicate var names when copying them into the vars array and eliminate them? I need the same var name to occur only once.

    Thanks in advance.

  13. #13
    Fear the Reaper...
    Join Date
    Aug 2005
    Location
    Toronto, Ontario, Canada
    Posts
    625
    Why not just compare the read variable on every iteration with all the variables you've read up to then ?
    Teacher: "You connect with Internet Explorer, but what is your browser? You know, Yahoo, Webcrawler...?" It's great to see the educational system moving in the right direction

  14. #14
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    I presume, U are also working on a database aplication.
    I think U can do something like this :
    1) " Cut " that column in the file that representing the "key" attribute and paste it in a file
    2) "grep" the key value in that file every time U insert. if it returns 0 , that key vakue exists. else, if doesnt , U can copy it into the file.
    3) At the end of each operation on the file, update the file containing the key attributes.

    But,this does have a drawback of creating more files.


    hey, sorry if I am changing the topic a little bit here, but looking thorugh the watch glass the other way around,
    if I have to insert such lines into files though my C program,
    if I do,
    Code:
      system("echo $var1 $var2 ... >> $file ");
    It only adds the fresh line at the point where the EOF is. But, if i want to add this fresh line, say 10 lines after the point where the EOF is , how do i do it?
    In the middle of difficulty, lies opportunity

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 22
    Last Post: 12-23-2008, 01:53 PM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  4. reading from a text file help......
    By jodders in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2005, 12:51 PM