首页 > 解决方案 > fputs 在开头插入无效数据

问题描述

我的输入文件包含这种格式的产品集合:

name
price
symbol

示例文件是:

Ball
6.24
u

我想读取文件,将文本解析为struct,并用相同的元素重写文件,但没有符号u。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

struct Product
{
    char name[30];
    char amount;
    double price;
};

int main()
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    struct Product products[100];

    fp = fopen("magazyn.txt", "r+");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    int counter = 0;
    int amount = 0;
    while ((read = getline(&line, &len, fp)) != -1) {
        if (counter != 0 && counter % 3 == 0)
        {
            counter = 0;
            amount++;
        }

            if (counter % 3 == 0) {
                strcpy(products[amount].name, line);
            }

            if (counter % 3 == 1)
                products[amount].price = atof(line);

            if (counter % 3 == 2)
                products[amount].amount = line[0];

        counter++;
    }

    truncate("magazyn.txt", 0);

    for(int i=0; i<amount; i++)
    {
        if (products[amount].amount != 'u') 
        {
            fprintf(fp, "%s\n%lf\n%c\n", 
            products[amount].name,
            products[amount].price,
            products[amount].amount);
        }
    }

    fclose(fp);

    if (line)
        free(line);

    return 0;
}

出于某种原因,我得到\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00Ball. 为什么会这样?

标签: c

解决方案


代码从文件中读取一些行,然后将新行附加到同一个文件(是的,它附加,见下文)。

调用truncate()将文件系统上的文件大小设置为 0。但它不会重置打开文件的当前文件偏移量。

因此,在编写新行时,它们被附加在先前内容的末尾,而先前的内容被替换为 0:它正在创建一个稀疏文件,一个有孔的文件,一个用 0 填充的孔。


推荐阅读