#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char* argv[]) {
char *filename = argv[1];
char *store = malloc(2);
FILE *fh = fopen(filename, "wb");
for(int i = 0; i < 100; i++) {
sprintf(store, "%u", i);
if (fh != NULL) {
fwrite (store, sizeof (store), 1, fh);
}
}
fclose (fh);
return 0;
}
我希望我的输出看起来像这样 - &gt; https://imgur.com/a/nt2ly。它目前产生的输出都是标记。
答案 0 :(得分:1)
垃圾的真正原因是fwrite
语句
fwrite (store, sizeof (store), 1, fh);
sizeof(store)
不字符串的大小。它是指针的大小。
除此之外,为store
分配2个字节是错误的。您忘记了一个2位数字作为字符串需要一个空终结符的空间,所以你要写一个字符太多了。
更小的问题:为什么要在循环中针对NULL
测试句柄?你可以在那种情况下退出。
同时测试参数长度(argc
)。
int main(int argc, char* argv[]) {
if (argc<2) exit(1); // protect against missing arg
char *filename = argv[1];
char store[50]; // use auto memory, faster & simpler, don't be shy on the size, don't shave it too close
FILE *fh = fopen(filename, "wb");
if (fh != NULL) { // test file handle here, not in the loop
for(int i = 0; i < 100; i++) {
// sprintf returns the number of printed chars, use this
// also use the proper format specifier for int
int nb_printed = sprintf(store, "%d", i);
// you may want to check the return value of fwrite...
fwrite (store, nb_printed, 1, fh);
}
fclose (fh);
return 0;
}
请注意,此代码将创建一个包含所有数字的二进制文件:
01234567891011...
很难用。我会执行sprintf(store, "%d ", i);
而不是在数字之间添加间距。
另请注意,如果您想在文件中书写字符,最好还是选择:
fprintf(fh,"%d ",i);
(但我想主要是学习使用fwrite
)