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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…