Thread: Reading data from a file and printing it

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    35

    Reading data from a file and printing it

    I am trying to read a file and print the data to the screen. This is what the code looks like so far.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char a[50];
    int i;
    
    
    
    FILE *fp;
    
    int main()
    {
    
    
    fp = fopen("PSV101data.rtf", "r");
    for (i=1; i <= 47; i++)
    {fscanf(fp, "%s\n", a[i]);
    printf("%s/n", a[i]);}
    fclose(fp);
    
    return 0;
    }

    This is the output

    (null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/n(null)/

    I am trying to just read one line at a time and output one line at a time. Any suggestions would be appreciated.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Step 1 is compile with some warnings enabled which tell you (for example) when you mess up printf/scanf

    $ gcc -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:13: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’
    foo.c:14: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’


    Next, indentation is king when it comes to reading code.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char a[50];
    int i;
    FILE *fp;
    
    int main()
    {
        fp = fopen("PSV101data.rtf", "r");
        for (i = 1; i <= 47; i++) {
            fscanf(fp, "%s\n", a[i]);
            printf("%s/n", a[i]);
        }
        fclose(fp);
    
        return 0;
    }
    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.

  3. #3
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    You need to check fp to make sure it is not NULL, aka you actually opened the file.

    Some suggested reading:
    Work with Files
    How to use EOF
    fgets()
    Last edited by AndrewHunter; 06-30-2011 at 12:02 PM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    Unfortunately, I havent programmed in C for a long while and I just dont understand the warning messages. Any suggestions?

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Linux Trojan
    I just dont understand the warning messages. Any suggestions?
    Basically, you are not using a string where you want to use a string. Think about what is the type of a[i], and what is expected for the %s format specifier.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Hmm.....where could I find some information on this?
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I would get rid of fscanf() and use fgets() instead. It's designed to read one row of text at a time:

    First, I'd increase the size of a[] to 100 char's, "bigger is better" for this.

    Then:

    Code:
    while((fgets(a, sizeof(a), filePointerName)), != NULL) {
       printf("%s", a);
    }
    If the number of rows in the file changes, or the lines ever get a bit longer, your program will still work.
    Last edited by Adak; 06-30-2011 at 12:17 PM.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Linux Trojan View Post
    Unfortunately, I havent programmed in C for a long while and I just dont understand the warning messages. Any suggestions?
    Yeah, start trying to understand the messages! Eg:

    foo.c:13: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’

    You have a filename and a line number. So you know the problem is here:

    Code:
            fscanf(fp, "%s\n", a[i]);
    Hopefully what "format ‘%s’" refers to is obvious enough (WRT scanf/printf functions, the template is sometimes called a "format string"). And the third argument is not sympatico with this format.


    Deciphering compiler/interpreter errors and warnings can take practice. Remember, the primary objective of the compiler is to produce an executable; the messaging is secondary and may face limitations because of the primary objective. The messages are still useful clues, however. Always enable warnings and aim to compile without getting any.
    Last edited by MK27; 06-30-2011 at 12:18 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    I finally got it
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char a[100];
    int i;
    
    
    
    FILE *fp;
    
    int main()
    {
    
    
    
    fp = fopen("PSV101data.rtf", "r");
    for (i=1; i <= 47; i++)
    {fgets(a, 70, fp);
    printf("%s", a);}
    fclose(fp);
    
    return 0;
    }
    I talked to some other people at some other forums and by hook and crook I devised this code. But something appears wrong in that previously I was taking code directly out of my Sams C book. Over the years I have found lots of conflicts with this book and the GNU C compiler. Is the GNU C compiler significantly different than "traditional" C ?

  10. #10
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by Linux Trojan View Post
    .... Over the years I have found lots of conflicts with this book and the GNU C compiler. Is the GNU C compiler significantly different than "traditional" C ?
    The GNU C compiler is C99 compliant. Depending on what year your C book was made it may be behind on the standardization; or if it is really old it might not be standard at all.

    As for your code some things to consider:
    Code:
    char a[100];
    int i;
    
    FILE *fp;
    There is no reason to have these variables exist with global scope so you should just move them into your main function since that is where they are used.

    Code:
    fp = fopen("PSV101data.rtf", "r");
    for (i=1; i <= 47; i++)
    ...
    You aren't checking to see if you actually have a handle to your file. If the file failed to open then you would cause an error when you went to read from it.

    Don't forget to indent your code, it will make it easier for you and others to read.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  11. #11
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    I just realized something about this code. It doesnt create a one diminsional array. It just creates a string variable. I was intending to create a string array that would store all the words I would read from the file. Thats what I wanted to do in the first code.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Linux Trojan View Post
    I just realized something about this code. It doesnt create a one diminsional array. It just creates a string variable. I was intending to create a string array that would store all the words I would read from the file. Thats what I wanted to do in the first code.
    What are you talking about?
    Code:
    char array[ X ]; /* an array of X characters */
    That is an array of characters. You can use it like a string by making sure it has a nul character appended to whatever you have there:
    Code:
    array[0] = 'd';
    array[1] = 'o';
    array[2] = 'g';
    array[3] = '\0'; /* now it's a string */
    That's all a string is: 0 or more characters terminated by a nul character.


    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Well a one dimensional array is a C style string. Maybe you want something more along the lines of this thread? If that is the case then it would be a 2 dimensional array, aka char myArray[LINES][WORDS];
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  14. #14
    Registered User
    Join Date
    Jun 2011
    Posts
    35
    My main languages are Basic and Fortran, so I am thinking in those terms. I am looking for this

    a(1) = Hello
    a(2) = World
    a(3) = Great
    a(4) = Day

    then print it to a file like

    Hello World
    Great Day

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    char *arrayofpointerstocharacters[ 4 ] =
    {
        "Hello",
        "World",
        "Great",
        "Day",
    };
    
    printf( "%s %s\n", arrayofpointerstocharacters[0], arrayofpointerstocharacters[1] );
    printf( "%s %s\n", arrayofpointerstocharacters[2], arrayofpointerstocharacters[3] );
    Having the answer is not the same thing as understanding it. You need to get a book or tutorial on arrays, once you understand that, then find one on pointers.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading in a file and printing out a graph from the data
    By levitylek in forum C Programming
    Replies: 3
    Last Post: 10-26-2010, 07:32 PM
  2. Reading from file and printing double data
    By hammari in forum C Programming
    Replies: 4
    Last Post: 07-14-2009, 07:02 AM
  3. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  4. printing data to a file
    By coralreef in forum C Programming
    Replies: 3
    Last Post: 11-02-2006, 08:10 PM
  5. problems reading data into an array and printing output
    By serino78 in forum C Programming
    Replies: 4
    Last Post: 04-28-2003, 08:39 AM