简体   繁体   English

逐行读取文件的已知结构,但长度未知

[英]Reading from file line by line known structure but length is unknown

I'm sorry to ask this question, because I found similar answered questions, but I'm having difficulty to understand how to read lines of unknown length but the structure is the same. 很抱歉提出这个问题,因为我发现了类似的回答问题,但是我很难理解如何读取长度未知但结构相同的行。

Each line is structured by the following: name:id:buyingPrice:sellingPrice:profit:quantity 每行的结构如下:名称:id:购买价格:销售价格:利润:数量

The names and IDs are strings while the rest are doubles. 名称和ID为字符串,其余为双精度。

My problem is I don't know how to setup a while that reads and stores each field, would it be possible to get a detailed explanation on how to accomplish this? 我的问题是我不知道如何设置一段时间来读取和存储每个字段,是否有可能获得有关如何完成此操作的详细说明?

Here's my read of the file(just with strings) : 这是我读取的文件(仅包含字符串):

file = fopen("fileData.txt", "rt");

if(file != NULL){
    char lineSize[128] = "";

    while(fgets(line, 128, file) != NULL){
        fscanf("%s:%s:%s:%s:%s:%s", string1, string2, string3, string4, string5, string6);

    }
    fclose(file);

你有没有想过使用strtok解析后的标记fgets

What I would use is the 'a' modifier for the scanf-format: Simply say 'fscanf("%as:%as:...", ...)', pass in the addresses of unallocated pointers and let fscanf malloc them for you. 我要使用的是scanf格式的'a'修饰符:简单地说'fscanf(“%as:%as:...”,...)',传入未分配指针的地址,然后让fscanf malloc他们为你。

This originated as a gnu extension, but AFAIK, it has made it into the C11 standart. 它起源于gnu扩展,但AFAIK使其成为C11标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM