2011-02-24 89 views
-1

我想問是否有任何方式可以通過它來檢索使用C編程的csv文件的列號?那些默認設置在csv文件中的數字以及行名稱,即:檢索csv文件的列ID

AB C .............. Z AA AB AC ......... ..

+1

歡迎來到C,那裏沒有什麼能阻止你,只要你樂意自己做。 – 2011-02-24 08:10:00

+0

我一定會這樣做,但需要一點指導 – tariq 2011-02-24 08:12:32

+0

CSV文件沒有列或行標識。你只是指列或行索引(0,1,2等)?你不能只保持一個櫃檯嗎? – 2011-02-24 08:19:01

回答

2

對不起蘭迪,但你有一些關於這一點的重大誤解。 CSV文件是非常多的文本文件,就像您在記事本中創建的恰好在文字/值之間有逗號一樣。如果你想在C閱讀它們,你可以使用scanf()的分析每一行 - 或者:

  • 寫一個程序,只能領域的一個特別的佈置工作:在...

    char name[128]; int age; int height_cm; int weight_kg; 
    
    while (scanf("%.128[^,],%d,%d,%d", name, &age, &height_cm, &weight_kg) == 4) 
    // do something with the values just read... 
    
  • 嘗試解析領域的各類直到你得到一個錯誤:

    char buffer[128]; 
    char delimiter; 
    int num_fields; 
    
    while ((num_fields = scanf("%.128[^,]%c", buffer, delimiter)) >= 1) 
    { 
    // use e.g. strtod to see if the field might be reasonably interpreted as a double 
    ... 
    
    if (num_fields == 1 || delimiter != 'c') 
        break; // end of line... 
    } 
    

編輯迴應評論/ q問題如下:

對不起 - 我只是不明白你在問什麼。什麼是「增加」數據?如果你的意思是文件有不同的行代表不同的行,並且有多個列,那麼是的,這是正常的,它可以通過我上面列出的方法進行分析。如果你的意思是詢問「你怎樣才能保存行/列以供將來處理」,那麼你可以創建一個包含字段的結構(如果你知道要對列名和類型進行硬編碼),或者使用一個數組(可能是char數據)。然後,您可以爲這些結構/數組創建一個數組(或鏈接列表,如果您有一個庫)。例如:

static const int Max_Persons = 1000; 

struct Person { char name[128]; int age; int height_cm; int weight_kg; }; 

Person persons[Max_Persons]; 
int num_persons = 0; // how many read from CSV file so far? 

while (scanf("%.128[^,],%d,%d,%d", 
      persons[num_persons].name, &persons[num_persons].age, 
      &persons[num_persons].height_cm, 
      &persons[num_persons].weight_kg) == 4) 
    if (++num_persons == Max_Persons) 
    { 
     printf("WARNING: can only handle the first %d people, ignoring rest\n", 
       Max_Persons); 
     break; 
    } 

這(從標準輸入 - 切換到使用fopen()和fscanf()函數,如果你想直接從指定的文件讀取)讀取多達MAX_LINES「人」行。

如果您不知道使用前面列出的替代(更復雜)方法需要的數據的數量和類型:嘗試傳遞每個字段直至發生故障,檢查逗號分隔結束字段與文件結束。我的頭頂和未經測試的,如:

struct Field { char buf[Max_Field_Len]; }; 
struct Row { Field r[Max_Columns]; }; 
Data Row[Max_Rows]; 
int num_columns = 0; 
int current_column = 0; 
int num_rows = 0; 
int num_fields; 
char delimiter; 
while ((num_fields = scanf("%[^,]%c", Row[num_rows][current_column].buf, &delimiter)) >= 1) 
{ 
    if (++current_column > num_columns) 
     num_columns = current_column; 
    if (num_fields == 2 && delimiter != ',') 
    { 
     current_column = 0; 
     ++num_rows; 
    } 
    else if (num_fields == 1) 
     break; // end-of-file 
} 
+0

託尼先生非常感謝。實際上在我的程序中,數據將在兩個方向上增加,即在行和列中是他們處理它的一種方式。謝謝 – tariq 2011-02-24 09:22:24

+0

@randy:我試圖在編輯中添加更多的細節。 – 2011-02-24 09:53:14

+0

謝謝Tony先生非常感謝您的幫助和關心。實際上我在運行時填寫csv文件中的數據數據將被更新爲數字dnt有預定義的字段,即列名稱和行名稱。在運行時,我不得不添加新的柱或行,但問題是,例如,我有第1行有3填充然後我移動到第2行填充讓我們說2列,但如何移動到指針再次行1填充第4列謝謝 – tariq 2011-02-24 10:09:45