[英]How to read from a file.csv and save every value in a string of array C
I have a file with 6.321.078 records, they are formed by couple of integers separated by a comma.我有一个包含 6.321.078 条记录的文件,它们由用逗号分隔的几个整数组成。 My aim is to read line by line and save it inside a char array (so, strings).
我的目标是逐行读取并将其保存在字符数组中(因此,字符串)。 My trouble is , when I run
sscanf()
it doesn't work.我的问题是,当我运行
sscanf()
它不起作用。 I think that this is the problem but I'm not sure that is the only one.我认为这是问题所在,但我不确定这是唯一的问题。 I know that the file contain INT, but I need to save every line such as string.
我知道该文件包含 INT,但我需要保存每一行,例如字符串。 What can I do and why does not it work?
我能做什么,为什么它不起作用? (There is an example of my file.csv below)
(下面是我的file.csv的示例)
main.c :主文件:
int main() {
FILE *fd;
char *arr;
arr = (char *)malloc(6321078);
for (int k = 0; k < 6321078; k++) {
arr[k] = calloc(20, sizeof(char));
}
char *r;
int pos = 0;
int n;
fd = fopen("file.csv", "r");
if (fd == NULL) {
perror("Error");
exit(1);
}
while (fgets(r, sizeof(r), fd) != NULL) {
sscanf(r, "%s", arr[pos]);
printf("%s", arr[pos]);
pos++;
}
}
Example of file.csv: file.csv 示例:
A pointer to array of 20 could be used char (*arr)[20]
可以使用指向 20 个数组的指针
char (*arr)[20]
Then allocate memory for the number of records.然后为记录数分配内存。
Use fgets
to read directly from the file into each record.使用
fgets
直接从文件读取到每条记录。
When done, close the file and free the memory.完成后,关闭文件并释放内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 6321078
#define LEN 20
int main ( void) {
char (*arr)[LEN] = NULL;
int pos = 0;
FILE *fd = NULL;
if ( NULL == ( fd = fopen("file.csv", "r"))) {
perror("Error");
exit ( EXIT_FAILURE);
}
if ( NULL == ( arr = calloc ( SIZE, sizeof *arr))) {
fclose ( fd);
fprintf ( stderr, "calloc problem\n");
exit ( EXIT_FAILURE);
}
while ( pos < SIZE && fgets ( arr[pos], sizeof arr[pos], fd)) {
printf ( "%s", arr[pos]);
++pos;
}
fclose ( fd);
free ( arr);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.