Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

scanf - fopen reading Invalid argument C

I can't seem to find an answer to the fopen issue. It seems to be common, but everything I'm trying is not working, from what I have read this seems to be caused by a trailing newline, but I'm not sure:

The aim is to move from the hardcoded filename (which is commented) to the command line input for the file name

any help would be much appreciated

My code

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

int main( int argc, char *argv[] )
{

    setbuf(stdout, NULL);

    struct Person { char lname[20]; char fname[20]; int id; };
    int N1, i ;
    struct Person *p;


//    char filename[] = "../src/students.csv" ;
//
//    FILE *str = fopen( filename, "r") ;
//    if (str==NULL) {
//        perror(filename) ;
//        exit(-1) ;
//    }


    printf("Please input file name:"); // Asks user to enter file name.
    FILE *str2 = fopen(argv[1], " r"); // File opened for reading
    printf("%p", str2);
    if (str2 == NULL) { // If issue opening file display the error.
        perror(argv[1]);
        exit(-1);

    }

    fscanf( str2, "%d
", &N1 ) ;

    p = (struct Person*)calloc( N1 , sizeof(struct Person) ) ;
    if (p==NULL) {
        fprintf(stderr, "Can't allocate %d structs -- exiting.
", N1 ) ;
        exit(-1) ;
    }

    for ( i=0 ; i<N1 ; i++ ) {
        fscanf( str2, " %[^,],%[^,],B%d", p[i].lname, p[i].fname, &(p[i].id) );
    }

    fclose(str2) ;

    /* Access the array... Just like a static array */
    printf("%s, %s, B000%d
", p[4].lname, p[4].fname, p[4].id) ;

    free(p) ;

    return 0;
}

studnets.csv

bob  hope    B0011001  jim real    B0011002  dean    egan    B0011003  mary    Sherri  B0011004  harry   full    B0011005  peg max B0011006  sun lee B0011007  bill    bob B0011008


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...