gpt4 book ai didi

c - Fputs 在开头插入无效数据

转载 作者:行者123 更新时间:2023-11-30 18:33:49 25 4
gpt4 key购买 nike

我的输入文件包含以下格式的产品集合:

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\00球。为什么会发生这种情况?

最佳答案

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

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

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

关于c - Fputs 在开头插入无效数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54638482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com