用C语言从文件中读取两个不同的列并将它们存储在两个不同的数组中?
我不太熟悉C中的文件处理。我有一个.txt文件,其中包含以下内容:用C语言从文件中读取两个不同的列并将它们存储在两个不同的数组中?,c,arrays,C,Arrays,我不太熟悉C中的文件处理。我有一个.txt文件,其中包含以下内容: 135.33208225150605 OK 165.1233490789463 OK 245.2329542568199 OK 301.9041144959863 D FILE *fp; fp = fopen("protocol1QT.seq", "r"); int i; for(i=0;i<=148;i++){ fgets(buff,sizeof(buff),fp); char *buffcopy =
135.33208225150605 OK
165.1233490789463 OK
245.2329542568199 OK
301.9041144959863 D
FILE *fp;
fp = fopen("protocol1QT.seq", "r");
int i;
for(i=0;i<=148;i++){
fgets(buff,sizeof(buff),fp);
char *buffcopy = malloc(strlen(buff) + 1);
if(buffcopy == NULL) {fprintf(stderr, "out of memory\n"); exit(1); }
strcpy(buffcopy, buff);
line[i] = buffcopy;
}
fclose(fp);
FILE *fp;
fp = fopen("protocol1QT.seq", "r");
int i;
double dv;
for(i=0;i<=148 && fscanf(fp, "%lf %[^\n]", &dv, buff)==2;i++){
char *buffcopy = malloc(strlen(buff) + 1);
if(buffcopy == NULL) {fprintf(stderr, "out of memory\n"); exit(1); }
strcpy(buffcopy, buff);
string_array[i] = buffcopy;//char *string_array[149];
numbers[i] = dv; //double numbers[149];
}
fclose(fp);
我想将带有数字的列存储在一个双数组中,将字符串列存储在另一个字符串数组中
我是这样做的:
135.33208225150605 OK
165.1233490789463 OK
245.2329542568199 OK
301.9041144959863 D
FILE *fp;
fp = fopen("protocol1QT.seq", "r");
int i;
for(i=0;i<=148;i++){
fgets(buff,sizeof(buff),fp);
char *buffcopy = malloc(strlen(buff) + 1);
if(buffcopy == NULL) {fprintf(stderr, "out of memory\n"); exit(1); }
strcpy(buffcopy, buff);
line[i] = buffcopy;
}
fclose(fp);
FILE *fp;
fp = fopen("protocol1QT.seq", "r");
int i;
double dv;
for(i=0;i<=148 && fscanf(fp, "%lf %[^\n]", &dv, buff)==2;i++){
char *buffcopy = malloc(strlen(buff) + 1);
if(buffcopy == NULL) {fprintf(stderr, "out of memory\n"); exit(1); }
strcpy(buffcopy, buff);
string_array[i] = buffcopy;//char *string_array[149];
numbers[i] = dv; //double numbers[149];
}
fclose(fp);
文件*fp;
fp=fopen(“协议1QT.序列”,“r”);
int i;
对于(i=0;i可以用strtok()
将其分开,或者如果它只是这个简单的例子,可以像这样使用sscanf()
char text[10]; // more if it could be larger
float number;
if (sscanf(line, "%f%9s", &number, text) == 2)
process_columns(number, text);
另外:在fgets()
之前,检查fp
中的NULL
,并将fgets()
置于条件中。类似如下:
135.33208225150605 OK
165.1233490789463 OK
245.2329542568199 OK
301.9041144959863 D
FILE *fp;
fp = fopen("protocol1QT.seq", "r");
int i;
for(i=0;i<=148;i++){
fgets(buff,sizeof(buff),fp);
char *buffcopy = malloc(strlen(buff) + 1);
if(buffcopy == NULL) {fprintf(stderr, "out of memory\n"); exit(1); }
strcpy(buffcopy, buff);
line[i] = buffcopy;
}
fclose(fp);
FILE *fp;
fp = fopen("protocol1QT.seq", "r");
int i;
double dv;
for(i=0;i<=148 && fscanf(fp, "%lf %[^\n]", &dv, buff)==2;i++){
char *buffcopy = malloc(strlen(buff) + 1);
if(buffcopy == NULL) {fprintf(stderr, "out of memory\n"); exit(1); }
strcpy(buffcopy, buff);
string_array[i] = buffcopy;//char *string_array[149];
numbers[i] = dv; //double numbers[149];
}
fclose(fp);
文件*fp;
fp=fopen(“协议1QT.序列”,“r”);
int i;
双dv;
对于(i=0;i