将文件解析为数组

时间:2015-06-02 10:34:54

标签: c parsing text-files

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

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

基本上是,

Item Code;Item Name;Price per unit;Quantity

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

2 个答案:

答案 0 :(得分:2)

首先使用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);

答案 1 :(得分:1)

您可以尝试以下代码:

#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中,包括&#39; \ n&#39;和其他特殊字符。如果您不希望特殊字符在while循环中添加必要条件。

相关问题