Thread: Reading lines separately from a file.

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    36

    Reading lines separately from a file.

    Hi all!

    During my OS assignment, I'm having a little problem regarding filing. The problem is that I'm to read each line in a separate array and after that perform further operations. I've initially read the entire file in a char array and after that I intend to split it up accordingly. The file is in the following format:

    P1 0
    12 2 21 2 12 32 18
    P2 9
    13 17 3 21 45 67 21

    (and so on)

    I've written the following code:

    Code:
    (Variables definitions and all)
    
    f=fopen ("umer.txt","r");
    if (!f)
          printf ("Could not open the file.\n");
    while (fgets (s,'\n',f)!=NULL)
    {
          if (s[i] == 'P')
          {
                processes++;
          }
          printf ("%s", s);
    }
    printf ("processes are: %d\n", processes);
    printf ("\n");
    fclose(f);
    
    while (s[i]!='\n')
    {
          printf ("char is: %c\n", s[i]);
          i++;
          printf ("-%d-", i);
    }
    But when I output the supposedly initial charaters from the array s[i] (which contains the entire file supposedly), it outputs 4,5,7,6. (It should output the first line of the file, i.e P1 (a tab) 0)

    What should I do? Any help would be highly appreciated.

    Thanks.

  2. #2
    Make Fortran great again
    Join Date
    Sep 2009
    Posts
    1,413
    Where is i in the midst of this? You can't just use the same value for i the whole time.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
    fgets (s,'\n',f)
    you should really start reading the reference guide instead of dropping random parts of the code together in hope that it will somehow work...

    magic is not applicable to programming... (if you are interested in the results of course)
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Registered User
    Join Date
    Aug 2009
    Posts
    36
    It's actually:
    Code:
    fgets (s,1000,f)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Reading Lines from File Issue (integers and character strings)
    By kbfirebreather in forum C Programming
    Replies: 4
    Last Post: 10-17-2009, 02:02 PM
  3. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM