c - 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
. 为什么会这样?
解决方案
代码从文件中读取一些行,然后将新行附加到同一个文件(是的,它附加,见下文)。
调用truncate()
将文件系统上的文件大小设置为 0。但它不会重置打开文件的当前文件偏移量。
因此,在编写新行时,它们被附加在先前内容的末尾,而先前的内容被替换为 0:它正在创建一个稀疏文件,一个有孔的文件,一个用 0 填充的孔。
推荐阅读
- javascript - how to call vuejs function from seperate javascript function
- jquery - Update bindings when element is updated outside angular
- excel - 功能化事件驱动的无模式用户窗体类
- javascript - 如何在搜索栏中添加 X 标签
- python - How can I detect a long touch from an item in kivymd?
- dailymotion-api - Dailymotion doesn't let me upload 10 video per day or even a week
- javascript - 如何在 JAVASCRIPT 中使用 array_push()?
- javascript - 有人可以解释为什么此代码返回 6 6 6 6 6 而不是 1 2 3 4 5
- postgresql - PostgreSQL Function Error: No function matches the given name and argument types. You might need to add explicit type casts
- javascript - 为什么在 JavaScript 函数体内调用 await 需要异步?