fprintf 在开头打印一堆 NULL
typedef struct record
{
float field1;
char *name;
} record;
void printRecordsTo(record **s, char *fileName, int size)
{
initializePrinter(fileName);
int i = 0;
while (i < size)
{
printRecordToFile(s[i]);
i++;
}
closePrinter();
}
static int delete = 0; // TODO: Remove
void printRecordToFile(record *r)
{
if (!file)
{
puts("Printer not initialized");
exit(1);
}
printf("%d %s", delete ++, toString(r)); // prints all correctly to stdout
fprintf(file, "%s", toString(r)); // includes many NULLs
}
char *toString(record *s)
{
float field1 = s->field1;
int len = 4;
char *field1Str = malloc(len + 1);
snprintf(field1Str, len + 1, "%f", field1);
char *name = s->name;
char *buf = malloc((1024) * sizeof(char));
snprintf(buf, 1023, "%s%s%s%s%s\n", "(", name, ", ", field1Str, ")");
return buf;
}
我不明白为什么 fprintf 对于大文件(大小约为 1000 条记录)打印许多 NULL。该函数对于我使用的小文件(大小约为 20 条记录)运行良好。我针对正常的 printf 进行了测试,它可以正确打印记录的字符串表示形式。
typedef struct record
{
float field1;
char *name;
} record;
void printRecordsTo(record **s, char *fileName, int size)
{
initializePrinter(fileName);
int i = 0;
while (i < size)
{
printRecordToFile(s[i]);
i++;
}
closePrinter();
}
static int delete = 0; // TODO: Remove
void printRecordToFile(record *r)
{
if (!file)
{
puts("Printer not initialized");
exit(1);
}
printf("%d %s", delete ++, toString(r)); // prints all correctly to stdout
fprintf(file, "%s", toString(r)); // includes many NULLs
}
char *toString(record *s)
{
float field1 = s->field1;
int len = 4;
char *field1Str = malloc(len + 1);
snprintf(field1Str, len + 1, "%f", field1);
char *name = s->name;
char *buf = malloc((1024) * sizeof(char));
snprintf(buf, 1023, "%s%s%s%s%s\n", "(", name, ", ", field1Str, ")");
return buf;
}
I can't figure out why many NULLs are being printed by the fprintf for large files (of size ~1000 records). The function works fine for the small files (of size ~20 records) I used. I tested it against normal printf which prints the string representations of records correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从源代码中删除
toString()
函数,它是多余的。在
printRecordToFile()
中使用以下语句为结构属性/成员使用有意义的名称。
如果您仍然看到垃圾值,那么您可能需要使用调试器来找出结构数据被损坏的位置。根据现有信息,我们只能猜测。
使用Valgrind来跟踪内存错误和内存错误泄漏。对于 C 程序员来说,这是一个非常漂亮的工具。
Drop
toString()
function from source, it's redundant.Use below statements instead in
printRecordToFile()
Use meaningful names for structure attributes/members.
If you're still seeing garbage values, then perhaps you need to sit with a debugger to find out where structure data is being corrupted. With the info at hand we can only guess.
Use Valgrind to trace memory error & leaks. It's a pretty nifty tool for C programmers.