trouble reading data from a file

This is a discussion on trouble reading data from a file within the C Programming forums, part of the General Programming Boards category; hi i am trying to read data from a file which is arranged as follows item1 item2 item3 etc etc ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    7

    trouble reading data from a file

    hi i am trying to read data from a file which is arranged as follows

    item1
    item2
    item3
    etc
    etc
    etc

    i am trying to read this then reproduce it on the console window line by line i have only been able to scan it all then display it all in one line in the console but i need to reproduce it line by line

    here is the code im using is there a way i can change it do do this? i am very new to c.

    the "if f(open) = fail" bit i stole straight out a text book by the way


    Code:
    #include <stdio.h>
    #include <unistd.h>
    
    int main(void)
    {
      int i;
      FILE *fp; 
      
      if ((fp=fopen("datafile", "r")) == NULL)
        {
          fprintf(stderr, "Failed to open file\n");
          exit(1);
        } else 
          {
    	{
    	  char input[1000];
    	  rewind(fp);
    do
    	 { i = fscanf(fp, "%s", input);
    	  printf("%s\n", input);
    	 }
    while(i !=EOF);
    
    	}
    	fclose(fp);
          }
      return 0;
    }
    Last edited by bob56; 03-16-2005 at 02:09 PM.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,164
    fgets() will read exactly one line of text from the file at a time. You might want to do a search on this forum for fgets() if you haven't used it before.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    thansk for your reply yeh i was looking at fgets thinking that would be good but what i dont understand is where you tell the call what line to read from is it a number? l

    i got this call from another thread

    Code:
     char line[80];
       
       if ( fgets( line, sizeof(line),stdin ) != NULL )
       {
          printf("%s...\n",line);
       }
    where do i tell c what line to access in the file?

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,164
    You can't. FILE pointers just work with streams. To C, the file just looks like one long line of bytes. However, lines are separated by newlines ('\n') and fgets() picks up on that. So the first call to fgets() after opening the file will read all the characters up until it reaches a '\n' character. The next call to fgets() reads everying after that first '\n' up until it reaches another '\n'. So the file system has no clue what a line is at the level you're talking about. What you can do is use fgets() in a loop. So say you want to read line 5, call fgets() 5 times and then the buffer will hold the 5th line of the file. Does that make sense?
    If you understand what you're doing, you're not learning anything.

  5. #5
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    right kinda yeh so if i just modify that code to say

    Code:
     char line[80];
       do
    {
       if ( fgets( line, sizeof(line,stdin ) != NULL )
       {
          printf("%s...\n",line);
       }
    }
    while(i !=EOF);
    will this loop through the whole file and print each line ive tried it but getting errors
    "too few functions to fgets" would this idea work?

    wait ive just relised that i does not exist now that the code has bene changed how can i tell it to keep looping until the end of file is reached?

  6. #6
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Pair up your parentheses.
    Code:
    if ( fgets( line, sizeof(line,stdin ) != NULL )
    Try this.
    Code:
    char line[80];
    while ( fgets( line, sizeof line, stdin ) != NULL )
    {
       printf("%s...\n",line);
    }
    [edit]Before you ask: getting rid of the newline.
    Last edited by Dave_Sinkula; 03-16-2005 at 03:35 PM. Reason: Added FAQ link.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  7. #7
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    hmm nope doesnt seem to be working when i use that code above it just seems to print out "..." every time you hit the return button and goes on for ever

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Replace stdin your stream fp.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    brilliant thank you guys great job

  10. #10
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    You seem to have most of the program, but you are having troubles organizing everything. what i would do i
    Code:
    #define  datafile   30
    that will be the max character length of your filename. Then declare
    Code:
    char  name[datafile];
    This is just a string to hold the name of the file.
    Then i would just use
    Code:
    gets(name);
    to read the string.
    Then to be able to account for an error id use
    Code:
    if ((fp = fopen(name, "r")) == NULL)
    	{
    		printf("Cannot open %s\n", name); 
    		exit(1);	/* End execution with  error code */
    	}
    Then to read the file we can use
    Code:
    while((i = getc(fp)) != EOF) 
    		putchar(i);/*display the numbers*/
    Then you just close the file after your done with it. Hope this helps
    When no one helps you out. Call google();

  11. #11
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    oooooh one last question dont know if this would be possible somehow but could you read 2 lines print them on the cosole in one line then go on to the next two lines print the on the next line of the console if you know what i mean so text file is like

    item1
    item2
    item3
    item4
    .
    .
    .

    and the cosole will display
    item 1 item 2
    item 3 item 4

    is this possible ?

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
       FILE *file = fopen("datafile", "r");
       if ( file )
       {
          char line1[80], line2[80];
          for ( ;; )
          {
             char *newline;
             if ( fgets(line1, sizeof line1, file) == NULL )
             {
                break;
             }
             newline = &line1[strlen(line1) - 1];
             if ( *newline == '\n' )
             {
                *newline = '\0';
             }
             if ( fgets(line2, sizeof line2, file) == NULL )
             {
                break;
             }
             newline = &line2[strlen(line2) - 1];
             if ( *newline == '\n' )
             {
                *newline = '\0';
             }
             printf("%s %s\n", line1, line2);
          }
          fclose(file);
       }
       return 0;
    }
    
    /* my output
    item1 item2
    item3 etc
    etc etc
    */
    Last edited by Dave_Sinkula; 03-16-2005 at 04:00 PM. Reason: Added color.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  13. #13
    Registered User
    Join Date
    Mar 2005
    Posts
    7
    hi thanks for that piece of code works a treat just a couple of questions aboutwhat things do

    Code:
    for (;;)
    what does this do ?

    and also
    Code:
    newline = &line1[strlen(line1) - 1];
             if ( *newline == '\n' )
             {
                *newline = '\0';
             }
    here i have a rough idea but not sure what is actually going on
    thanks

  14. #14
    ---
    Join Date
    May 2004
    Posts
    1,379
    Its finding out the length of the line, seeing if it has a carriage return '\n' then replacing it with null '\0'

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by bob56
    hi thanks for that piece of code works a treat just a couple of questions aboutwhat things do

    Code:
    for (;;)
    what does this do ?
    It is an unconditional loop. Instead the loop is broken within the loop body when one of the input attempts fails.
    Quote Originally Posted by bob56
    and also
    Code:
    newline = &line1[strlen(line1) - 1];
             if ( *newline == '\n' )
             {
                *newline = '\0';
             }
    here i have a rough idea but not sure what is actually going on
    thanks
    It is similar to what is shown in the FAQ, and as already pointed out, it is used to strip the terminating newline character if it is found.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. Please Help Reading Data From A File
    By NickHolmes in forum C Programming
    Replies: 5
    Last Post: 05-29-2005, 11:24 PM
  3. Reading encrypted data from file
    By cctoombs in forum C Programming
    Replies: 2
    Last Post: 02-13-2005, 01:59 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 02:58 PM

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