我的输入文件包含以下格式的产品集合:
rollback: TX:ID:ourhostname-42322-1582645535088-4:310:2 syncCount: 0
Error occured while processing sync command: TransactionInfo {commandId = 7363, responseRequired = true, type = 2, connectionId = ID:ourhostname-42322-1582645535088-4:310, transactionId = TX:ID:ourhostname-42322-1582645535088-4:310:2}, exception: javax.jms.JMSException: Transaction 'TX:ID:ourhostname-42322-1582645535088-4:310:2' has not been started.
javax.jms.JMSException: Transaction 'TX:ID:ourhostname-42322-1582645535088-4:310:2' has not been started.
示例文件为:
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;
}
。为什么会这样?
答案 0 :(得分:3)
代码正在从文件中读取一些行,然后将新行添加到同一文件中(是的,它会追加,请参见下文)。
调用truncate()
将文件系统上的文件大小设置为0。但这不会为打开的文件重置当前文件偏移。
因此,在编写新行时,它们会附加在前一个内容的末尾,而前一个内容将替换为0:它将创建一个稀疏文件,该文件具有孔,孔填充为0。