如何从文件C创建一个int字符串



我有一个file.csv,它包含一对用逗号分隔的int。我的目标是从文件(fgets(中读取数字,并将它们像字符串一样放入char (*arr)中。问题是它在逗号后面加了更多的数字。我该怎么办?

示例电话号码:9514902846arr:9514902845962

main.c

#define SIZE 10
#define LEN 20

int main(){
char (*arr)[LEN] = NULL;
int pos = 0;
FILE *fd = NULL;
fd = fopen("file.csv", "r");
arr = calloc ( SIZE, sizeof *arr);
while ( pos < SIZE && fgets ( arr[pos], sizeof arr[pos], fd)) {
printf ("%s", arr[pos]);
++pos;
}
fclose ( fd);
free ( arr);
return 0;
}

文件.csv

9514902,846
1134289,572
7070279,994
30886,48552
750704,1169
1385812,729
471548,3595
8908491,196
4915590,362
375309,212

我的输出:

9514902,845962
1134289,571587
7070279,993574
30886,485520
750704,116888
1385812,729300
471548,359462
8908491,19559
4915590,361558
375309,211958

您可以使代码更易于编写、维护和理解。正如我所看到的,您也不需要动态内存分配。

更改为

#define SIZE 10
#define LEN 20

int main(){
char arr[LEN] = {0};   // just define a char array, should be sufficient.
int pos = 0;
FILE *fd = NULL;
fd = fopen("file.csv", "r");
if (!fd) {                          // don't for get the error check
printf ("File handling errorn");
exit (-1);
}
while ( pos < SIZE && fgets ( arr[pos], LEN, fd)) {
printf ("%s", arr[pos]);
++pos;
}
fclose ( fd);
}

最新更新