[英]How to read the first entries of a CSV file in C?
我有一個看起來像這樣的csv文件:
Jake, 25, Montreal
Maria, 32, London
Alex, 19, New York
Jake, 22, Dubai
我正在嘗試實現的函數是find_name,它應遍歷每條記錄的第一個字段,並將其與正在搜索的名稱進行比較。
我嘗試了fgets,fscanf,但是代碼不起作用或者我遇到了分段錯誤。
這是我到目前為止:
void find_name(const char *csv_filename, const char *name){
FILE *csvFile = fopen(csv_filename, "r");
char word[1000];
if (csvFile == NULL)
exit(EXIT_FAILURE);
while ( !feof(csvFile) ) {
fscanf(csvFile, "%s%*[^,]", word);
if ( strcmp(word, name) == 0 )
printf("name found");
}
fclose(csvFile);
}
任何幫助表示贊賞。
編輯:我不想使用任何tokenizer功能,我寧願了解如何使用fscanf。
如果你一次只讀一個字段,那么處理一行的結尾變得相當棘手,所以建議你一次一行,比如:
int FieldScanCount = 0;
char city[1000];
int age = 0;
while ((FieldScanCount = fscanf(csvFile, "%1000[A-Za-z0-9 ],%i,%1000[A-Za-z0-9 ]\r\n", &word, &age, &city)) > 0) {
我假設每行末尾有一個\\ r \\ n,但根據你的文件,這可能只需要\\ n。
關於:
while ( !feof(csvFile) ) {
fscanf(csvFile, "%s%*[^,]", word);
if ( strcmp(word, name) == 0 )
printf("name found");
}
建議使用:
while ( fgets( word, sizeof(word), csvFile ) )
{
char *token = strtok( word, ", " );
if( strcmp( token, name ) == 0 )
{
printf("name found");
}
}
但是,如果你不想使用strtok()
那么建議:
while ( fgets( word, sizeof word, csvFile ) )
{
char *comma = strchr( word, ',');
*comma = \0';
if( strcmp( word, name ) == 0 )
{
printf("name found");
}
}
但是,如果你真的想使用scanf()
系列函數:
while ( fgets( word, sizeof word, csvFile ) )
{
char possibleMatch[1000];
if( sscanf( "%999[^,]", word, possibleMatch ) == 1 )
{
if( strcmp( possibleMatch, name ) == 0 )
{
printf("name found");
}
}
}
但是,如果你真的想使用fscanf()
:
while ( fscanf( csvFile, "%999[^,]", word ) == 1 )
{
if( strcmp( word, name ) == 0 )
{
printf("name found");
}
//consume rest of input file line
int ch;
while( ( ch = getchar() ) != EOF && ch != '\n' ){;}
}
或者甚至更好:
while ( fscanf( csvFile, " %999[^,] %*[^\n]", word ) == 1 )
{
if( strcmp( word, name ) == 0 )
{
printf("name found");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.