help please !

This is a discussion on help please ! within the C Programming forums, part of the General Programming Boards category; I am trying to read a file using pointers and this is all i get ! 54123132132 21 2152 22 ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    help please !

    I am trying to read a file using pointers and this is all i get !

    54123132132
    21
    2152
    22
    2
    2
    5212
    2






    #include <stdio.h>
    #include <stdlib.h>

    void traverse(void);

    /* Structure for printing the id.txt file */
    struct id_card {
    int ID;
    struct id_card *nextptr;
    };

    typedef struct id_card node;

    void traverse(void) {
    FILE *fp;
    node *currptr = NULL, *headptr = NULL, *prevptr = NULL;
    int NUM, i;

    fp = fopen( "id.txt","r" );
    if ( fp == NULL ) {
    printf( "Unabale to open id.txt file \n" );
    exit( 1 );
    }

    for(i = 1; i<=8; i++) {
    NUM = getc( fp );
    NUM = NUM-48;
    currptr = malloc( sizeof(node) );

    currptr->ID = NUM;
    currptr->nextptr = NULL;
    printf( "%d",NUM );

    if ( headptr == NULL ) {
    /* List is empty - start a new list */
    headptr = currptr;
    prevptr = currptr;
    } else {
    /* append to existing list */
    prevptr->nextptr = currptr;
    prevptr = currptr;
    }
    }

    currptr = headptr;
    while ( currptr != NULL ) {
    printf( "\n" );
    printf( "%d", currptr->ID );
    currptr=currptr->nextptr;
    }

    fclose( fp );
    }


    int main( ) {
    traverse();
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    22
    Hi,
    Tell me what is your expectation and how is your file contents look like.

    Better use fscanf()/fread()
    for file reading instead of getc().

    by
    A.Sebasti..

Popular pages Recent additions subscribe to a feed

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