Error after reading all words from a .txt

This is a discussion on Error after reading all words from a .txt within the C Programming forums, part of the General Programming Boards category; This program reads words from a dictionary text file and writes all of the words that end in 'man' to ...

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    9

    Error after reading all words from a .txt

    This program reads words from a dictionary text file and writes all of the words that end in 'man' to another file. I know this is probably a very strange way to do this but it's what I have after trying it a few ways.

    It works, and writes all the words to the file, but it crashes after reading through all of the words in the dictionary file. I don't know why (ms vc++ 6.0).

    Code:
    if ((dictfile = fopen("/aacraig/dict.txt", "r"))==NULL) {
    		printf("Cannot open this file\n");
    		exit(1);
    	}
    
    	
    
    	while(!feof(dictfile)) { 
    	
    		next_char = 0;
    		count=0;
    		for (i=0; next_char!=10; i++) {        /* read one line in */
    			fscanf(dictfile, "%c", &next_char);
    			array[i] = next_char;
    			count++;
    		}
    
    
    		//printf("count is %d\n", count);
    		wordfile = fopen("/aacraig/wordfile.txt", "a");
    
    		if ((array[count - 2] == 'n') && (array[count - 3] == 'a') 
    									  && (array[count - 4] == 'm'))
    			for(i=0; i<count; i++)
    				fprintf(wordfile, "%c", array[i]);
    		
    
    		printf("\n");
    		fclose(wordfile);
    
    	}
    
    	fclose(dictfile);

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>while(!feof(dictfile))
    This is not the way to control a read loop. You should use the return code from the read function to determine when you've reached EOF.

    Code:
    for (i=0; next_char!=10; i++) {        /* read one line in */
      fscanf(dictfile, "%c", &next_char);
      array[i] = next_char;
      count++;
    }
    This looks like a clear case for a buffer overflow. What happens when you reach EOF? (See my first point)

    >>array[count - 2]
    And if count == 0, where are you indexing too?!

    >>/* read one line in */
    If you want a line reading function, use fgets().
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    I got it to work like this, but it's really yucky and unsafe and all kinds of nasty stuff that you can imagine :-)
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
      int i;
      int count;
      char next_char;
      char array[10000];
      FILE *dictfile, *wordfile;
    
      if ((dictfile = fopen("input.txt", "r"))==NULL) {
        printf("Cannot open this file\n");
        exit(1);
      }
      
      while(!feof(dictfile)) {
        next_char = 0;
        count=0;
    
        for (i=0; next_char!='\n' && next_char != EOF; i++) {        /* read one line in */
          if (fscanf(dictfile, "%c", &next_char) != 1)
          {
            break;
          }
          array[i] = next_char;
          count++;
        }
        
        //printf("count is %d\n", count);
        wordfile = stdout;
        
        if ((array[count - 2] == 'n') && (array[count - 3] == 'a') 
          && (array[count - 4] == 'm'))
        {
          for(i=0; i<count; i++)
          {
            fprintf(wordfile, "%c", array[i]);
          }
        }
        
        printf("\n");
      }
      
      fclose(dictfile);
    
      return 0;
    }
    This way would be way better :-)
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
      char array[10000];
      FILE *dictfile, *wordfile = stdout;
    
      if ((dictfile = fopen("input.txt", "r")) == 0)
      {
        return 1;
      }
      
      while(fgets(array, sizeof array, dictfile) != 0)
      {
        if (strstr(array, "man") != 0)
        {
          fprintf(wordfile, "%s", array);
        }
      }
      
      fclose(dictfile);
    
      return 0;
    }
    *Cela*

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>for (i=0; next_char!='\n' && next_char != EOF; i++)
    >> if (fscanf(dictfile, "%c", &next_char) != 1)
    next_char won't get to be EOF as fscanf() won't populate it so.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>next_char won't get to be EOF as fscanf() won't populate it so.
    I plead insanity for doing that in the first place and then I plead stupidity for leaving it there when I posted :-)
    *Cela*

  6. #6
    Registered User
    Join Date
    Dec 2002
    Posts
    9
    Your 2nd program finds all words with man in it, like manual, etc. I guess that's what my problem with fgets() is. I can read all day what it does ( http://www.rt.com/man/fgets.3.html ) but I dont really know what it does

    Can you somehow break what fgets reads into an array so I can work with the last characters of that line? (obviously possible, I just dont know how).

    Thanks Hammer, I realized your bottom 2 points, and will have to read about the top 2.

  7. #7
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>Your 2nd program finds all words with man in it, like manual, etc.
    Sorry, I thought you wanted any word with man in it, try this :-)
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
      char array[10000];
      FILE *dictfile, *wordfile = stdout;
    
      if ((dictfile = fopen("input.txt", "r")) == 0)
      {
        return 1;
      }
     
      while(fgets(array, sizeof array, dictfile) != 0)
      {
        char *p = strchr(array, '\n');
    
        if (p != 0)
        {
          *p = '\0';
        }
    
        if (strcmp(array + (strlen(array)-3), "man") == 0)
        {
          fprintf(wordfile, "%s\n", array);
        }
      }
     
      fclose(dictfile);
    
      return 0;
    }
    *Cela*

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>work with the last characters of that line?
    They're the ones just before the terminating \0 character

    Here's a quick hack, showing how you might be able to test the last 3 chars of a string. Remember, if you use fgets(), get rid of, or at least account for the possible presence of a newline character in the buffer.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main (void)
    {
      char a[][20] = {"I am a man", "No youre not", "OK"};
      int i, len;
      
      for (i = 0; i < 3; i++)
      {
        len = strlen (a[i]);
        if (len > 3)
        {
          len -= 3;
          if (strcmp(&a[i][len], "man") == 0)
            printf ("found it\n");
          else
            printf ("didn't find it\n");
        }
        else printf ("Line too short\n");
      }
        
      
      return 0;
    }
    
    
    /*
     Program output
      found it
      didn't find it
      Line too short
     */
    [edit]Doh, beat by miles

    [edit2]
    >>(strlen(array)-3),
    What if strlen() returns 0?
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  9. #9
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>What if strlen() returns 0?
    You test it before using it of course. I'll just say that's an exercise for the reader and let you wonder if I meant to do it for simplicity or I forgot :-)

    ps: If it was bugging you, I forgot :-)
    *Cela*

  10. #10
    Registered User
    Join Date
    Dec 2002
    Posts
    9
    Thanks , will play with these. I'll have more newb questions soon. This stuff is finally starting to be fun.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading words using fread
    By -EquinoX- in forum C Programming
    Replies: 22
    Last Post: 05-05-2008, 02:09 PM
  2. reading words line by line from a file
    By -EquinoX- in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 12:34 AM
  3. I'm not THAT good am I?
    By indigo0086 in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 10-19-2006, 10:08 AM
  4. Reading lines from a .txt file
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 01-09-2002, 01:17 AM
  5. Reading from a .txt file or use arrays.
    By []--JOEMAN--[] in forum C++ Programming
    Replies: 3
    Last Post: 12-07-2001, 06:55 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21