【问题标题】:Parsing file into an array [duplicate]将文件解析为数组[重复]
【发布时间】:2015-08-16 02:28:14
【问题描述】:

美好的一天。不知道这个问题之前有没有被问过。任何人,我有一个内容如下的文本文件

AP0003;Football;13.50;90
AP0004;Skateboard;49.90;30

基本上是,

Item Code;Item Name;Price per unit;Quantity

我正在尝试将文本文件的内容放入一个数组中,但到目前为止我还没有运气。而且,我在 Stack Overflow 上找不到类似的东西(或者我的搜索参数可能不准确)。将不胜感激我能得到的任何帮助。我是 C 编程新手。

【问题讨论】:

  • 您的文件似乎是 CSV 格式。您需要一个 CSV 解析库。例如:stackoverflow.com/questions/7827274/… 及其所有重复项。
  • 我最终需要在 Linux 服务器上运行我的代码。 CSV 解析库也应该可以正常工作吗?
  • 如果该库适用于 -nix 系统,您也应该能够在 linux 机器上运行它。否则,如果您访问源代码,您只需在 linux 机器上重新编译即可。

标签: c parsing text-files


【解决方案1】:

首先使用fopen打开文件:

FILE* fp = fopen("NAME_OF_FILE.txt", "r"); // "r" stands for reading

现在,检查它是否打开

if(fp == NULL)                             //If fopen failed
{
    printf("fopen failed to open the file\n");
    exit(-1);                              //Exit program
}

假设这些是您存储行的数组,每个数据是:

char line[2048];                          //To store the each line
char itemCode[50]; 
char item[50];
double price;
int quantity;                             //Variables to store data

使用fgets 读取文件。它逐行消耗。把它放在一个循环中,当fgets 返回NULL 以逐行扫描整个文件时终止。然后使用sscanf 从扫描线中提取数据。在这种情况下,如果成功,它将返回 4:

while(fgets(line, sizeof(line), fp) != NULL) //while fgets does not fail to scan a line
{
    if(sscanf(line, "%[^;];%[^;];%lf;%d", itemCode, item, price, quantity) != 4) //If sscanf failed to scan everything from the scanned line
            //%[^;] scans everything until a ';'
            //%lf scans a double
            //%d scans an int
            //Better to use `"%49[^;];%49[^;];%lf;%d"` to prevent buffer overflows
    {     
         printf("Bad line detected\n");
         exit(-1);                          //Exit the program
    }
    printf("ItemCode=%s\n", itemCode);
    printf("Item=%s\n", item);
    printf("price=%f\n", price);
    printf("Quantity=%d\n\n", quantity);    //Print scanned items
}

最后,使用fclose关闭文件:

fclose(fp);

【讨论】:

    【解决方案2】:

    你可以试试这个代码:

    #include <stdio.h>
    #include <stdlib.h>
    int main() 
    {
     char str1[1000],ch;
     int i=0;
     FILE *fp;
     fp = fopen ("file.txt", "r"); //name of the file is file.txt
     while(1)
       {
        fscanf(fp,"%c",&ch);  
        if(ch==EOF) break;   //end of file
        else str[i++]=ch;    //put it in an array
        }    
     fclose(fp);   
     return(0);
    }
    

    这会将您的整个文件放入一个数组 str 中,包括 '\n' 和其他特殊字符。如果您不希望特殊字符在 while 循环中放置必要的条件。

    【讨论】:

    • 感谢您的建议。会试试看!
    • 无论如何你真的想要从文件到你的数组中的所有东西吗?我的意思是这对你有什么好处?
    • 嗯,基本上,我的任务要求我创建一个采购系统。因此,我需要将用户输入与文件中的“itemCode”进行比较。试图找出最好的方法是什么......
    • 那么您不需要将整个文件写入数组,只需将项目代码写入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多