[英]read csv file in C with commas inside strings
我有一個用逗號作為分隔符的 csv 文件,但是里面有帶逗號的字符串值,所以 mi 代碼也把它分開了
char buffer[1024];
int row = 0;
int column = 0;
while (fgets(buffer,1024, fp)) {
column = 0;
row++;
if (row == 1)
continue;
char* value = strtok(buffer, ",");
while (value) {
if (column == 0) {
printf("Titulo :");
}
if (column == 1) {
printf("\tAutor :");
}
if (column == 2) {
printf("\tanio :");
}
if (column == 3) {
printf("\testante_numero :");
}
if (column == 4) {
printf("\testante_seccion :");
}
if (column == 5) {
printf("\tpiso :");
}
if (column == 6) {
printf("\tedificio :");
}
if (column == 7) {
printf("\tsede :");
}
printf("%s", value);
value = strtok(NULL, ",");
column++;
}
printf("\n");
}
// Close the file
fclose(fp);
csv 文件的一行示例: “Structure and Interpretation of Computer Programs”,“Abelson, Sussman, and Sussman”,1996,4,“Lenguajes de Programacion”,2,“B”,“Vina del Mar”
我的 output: Titulo :“計算機程序的結構和解釋”作者:“Abelson anio:Sussman estante_numero:和 Sus sman”estante_seccion:1996 piso:4 edificio:“Lenguajes de Programacion”sede:2“B”“Vina del Mar”
我該如何修復我的代碼?
CSV 文件中的字段以逗號分隔,記錄以換行符終止。 因此,我們的想法是逐行讀取文件,識別定界逗號,但忽略嵌入的逗號。
下面的示例並不是一個完美的解決方案,它將實現 CSV 規范的所有規則,而只是一個如何使用提供的信息解析文件的示例。
如果文件包含 header 行,則可以讀取每個字段名稱並將其存儲在一個字符串數組中,以獲得更通用的方法。 此外,如果需要對數據進行一些進一步的操作(可能是排序),則可以使用結構。
包括一些注釋來解釋代碼。
#include <stdio.h>
#include <stdlib.h>
#define BUFF_SIZE 1024
#define NR_FIELDS 8
int main(void)
{
char buffer[BUFF_SIZE];
char *field[NR_FIELDS] = {"Titulo", "Autor", "Anio", "Estante numero", "Estante seccion", "Piso", "Edificio", "Sede"};
char *pos, *lastPos;
FILE *fp = fopen("file.csv", "r");
if (fp == NULL)
{
printf("Error opening the file.");
exit(1);
}
// read each line to a buffer
while (fgets(buffer, BUFF_SIZE, fp) != NULL)
{
int i = 0;
_Bool inString = 0;
pos = lastPos = buffer;
/* read characters from the buffer. If " is read, consider it beginning of the
string and ignore subsequent commas, until second " is read */
do
{
if (*pos == '\"')
inString = !inString;
/* if ',' is read or the end of the line is reached, while not inside a string,
consider it a field delimiter and print the field, preceded by field name */
if ((*pos == ',' || (*pos == '\0' && i == NR_FIELDS - 1)) && !inString)
{
printf("%s: %.*s", field[i++], pos - lastPos, lastPos);
if (*pos)
// add space between the fields if not at the end of the line
printf(" ");
lastPos = pos + 1;
}
} while (*pos++ && i < NR_FIELDS);
}
fclose(fp);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.