fgets after getc

This is a discussion on fgets after getc within the C Programming forums, part of the General Programming Boards category; i have something like this: Code: k = 0; while ( (c = getc(fp)) != EOF ) { if ( ...

  1. #1
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246

    fgets after getc

    i have something like this:
    Code:
    k = 0;
    while ( (c = getc(fp)) != EOF )
    	{
              if ( c == '\n')
    	     k++;
             }
    char dat[k][200];
    
    printf("\n%d\n",k);
    
    i = 0;
    while( fgets(dat[i++],sizeof dat[j],fp) != NULL )
    first i count '\n' in a file to know how large the array should be , so i use getc. then i want to put those lines in array with fgets.
    The problem is that fgets doesnt read the lines already read by getc and array is not filled with correct values.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >first i count '\n' in a file to know how large the array should be
    This will only work if all of the lines are as long as the first line, or shorter. If that's the case then you can simply rewind the file, clear error flags and start over:
    Code:
    rewind ( fp );
    My best code is written with the delete key.

  3. #3
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246
    thanks , it works
    This will only work if all of the lines are as long as the first line, or shorter
    i tried it with different files and it worked correctly, first line was shorter than others

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >i tried it with different files and it worked correctly
    If the first line is 20 characters to '\n' and the second line is 25 characters to the '\n', your output will not be correct because one line is split into two processing iterations.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets not working after fgetc
    By 1978Corvette in forum C Programming
    Replies: 3
    Last Post: 01-22-2006, 05:33 PM
  2. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  3. problem with fgets
    By Smoot in forum C Programming
    Replies: 4
    Last Post: 12-07-2003, 02:35 AM
  4. fgets crashing my program
    By EvBladeRunnervE in forum C++ Programming
    Replies: 7
    Last Post: 08-11-2003, 12:08 PM
  5. help with fgets
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-17-2001, 08:18 PM

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