我正在尝试读取格式如下示例的文件:
3 3 1.5 50
0 2 46.0 0
* 1 46.0 1
2 * 46.0 0
0 0 50.0 0
* * 42.0 0
2 2 36.1
2 1 42 0
0 1 48.0 0
1 0 48 0
首先,我想将文件的内容存储在字符串中。然后,我想扫描字符串并查看是否有星号*。由于某种原因,我无法将其存储为字符串。每当我尝试打印字符串时,它都会给我空行。有没有一种简单的方法可以从文件中读取数据并将其存储到字符串中?稍后我会将数值数据转换为数组。
代码片段:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *id; //Input Data
double *detect;
int nx, ny, i, j, k, n, count, t, frequency;
double a;
char val;
n = 0;
id = fopen(argv[1], "r");
frequency = atoi(argv[2]);
if(id){
fscanf(id, "%d %d %lf %d", &nx, &ny, &a, &tn);
}
detect = (double *) malloc(nx*nx*4*sizeof(double));
if(id){
for(i=0; i<2; i++){
fscanf(id,"%s", (detect+i));
}
}
//~ The rest of the code is left out ~
return 0;
}
最佳答案
您可以将数据放入这样的字符串中。
它使用以下内容:
-
fgets
从文件中读取每一行并将其存储在字符串缓冲区中。 -
malloc
在堆上为字符串、char *detect
分配空间。用途realloc
在需要时重新分配更多空间。 -
strcat
将buffer
附加到指针*detect
。 -
free
释放malloc()
请求的内存。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 100
#define STARTSIZE 10
int
main(int argc, char *argv[]) {
FILE *id;
char *detect;
char buffer[BUFFSIZE];
size_t slen, currsize = STARTSIZE, len = 0;
const char *separate = " ";
id = fopen(argv[1], "r");
if (!id) {
fprintf(stderr, "%s\n", "Error reading file");
exit(EXIT_FAILURE);
}
detect = malloc(currsize * sizeof(*detect));
if (!detect) {
printf("Error allocating memory\n");
exit(EXIT_FAILURE);
}
*detect = '\0';
while (fgets(buffer, BUFFSIZE, id) != NULL) {
slen = strlen(buffer);
len += slen-1;
if (slen > 0) {
if (buffer[slen-1] == '\n') {
buffer[slen-1] = '\0';
} else {
printf("Error: Exceeded Buffer length of %d.\n", BUFFSIZE);
exit(EXIT_FAILURE);
}
}
if (currsize == len) {
currsize *= 2;
detect = realloc(detect, currsize * sizeof(*detect));
if (!detect) {
printf("Error reallocating memory\n");
exit(EXIT_FAILURE);
}
}
strcat(detect, separate);
strcat(detect, buffer);
}
printf("Your string = %s\n", detect);
free(detect);
return 0;
}
关于c - 如何在C中将混合数据类型的文件读入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41117648/