[英]How to read a CSV file in C
我正在嘗試讀取以下格式的 CSV 文件:
5,455,78,5
12245,4,78
1,455,4557,1,8,9
我設法打開了文件,但我不知道如何解釋數據。 所有數據都寫在第一列,但我不知道有多少行或每行有多少條目。 這是我打開文件的代碼。
printf("File chosen is: %s",file);
int p=0;
FILE *myFile = NULL;
myFile = fopen(file,"r");
if (myFile == NULL)
{
exit(1);
}
if (myFile != NULL)
{
printf("\n\nFile read succesfully");
}
這應該解析您的 csv。 打開文件后,使用fgets讀取每一行。 循環直到 fgets 返回 NULL ,這表明無法讀取任何行並且您已到達文件末尾。 使用strtok從 fgets 解析您的行,使用逗號作為分隔符。
#include <stdio.h> // file handling functions
#include <stdlib.h> // atoi
#include <string.h> // strtok
...
char buffer[80];
while (fgets(buffer, 80, myFile)) {
// If you only need the first column of each row
char *token = strtok(buffer, ",");
if (token) {
int n = atoi(token);
printf("%d\n", n);
}
// If you need all the values in a row
char *token = strtok(buffer, ",");
while (token) {
// Just printing each integer here but handle as needed
int n = atoi(token);
printf("%d\n", n);
token = strtok(NULL, ",");
}
}
...
感謝您發布一些代碼,但您沒有提及您在讀入數據后希望如何處理數據。
我給你一些指點:
使用已知大小的數組從文件中讀取數據並將其緩沖以進行處理。 循環運行它。 例如
char buffer[1000];
while (fgets(buffer, sizeof (buffer), myFile))
{
char *data = strtok(buffer, ",");
printf("Data %s\n", data);
/* Further processing of data */
data = strtok(NULL, ",");
}
fclose(myFile);
使用strtok
處理該緩沖區以分離出您的字符串。 令牌是數據分隔符,應該是','
但我不清楚你是否也有換行符,但它需要保持一致。
處理上面返回的字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ",");
tok && *tok;
tok = strtok(NULL, ",\n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE *stream = fopen("yourfile.csv", "r");
int i = 0;
int j = 0;
printf("Choose a line to be given its elements: ");
scanf("%d", &j);
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = _strdup(line);
i++;
printf("Element %d would be %s\n", i, getfield(tmp, j));
free(tmp);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.