如何解决fopen 读取无效参数 C
我似乎找不到 fopen 问题的答案。这似乎很常见,但我尝试的一切都不起作用,从我读过的内容来看,这似乎是由尾随换行符引起的,但我不确定:
目的是从硬编码的文件名(已注释)移动到文件名的命令行输入
任何帮助将不胜感激
我的代码
#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\n",&N1 ) ;
p = (struct Person*)calloc( N1,sizeof(struct Person) ) ;
if (p==NULL) {
fprintf(stderr,"Can't allocate %d structs -- exiting.\n",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\n",p[4].lname,p[4].fname,p[4].id) ;
free(p) ;
return 0;
}
studnets.csv
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。