所以我试图编写一个带有3个命令行参数的程序,1。现有文件的名称,2。新文件的名称,3。从每行复制的字符数到新文件。
这是我到目前为止所做的:
int main(int argc, char *argv[]) {
int size = atoi(argv[3]); // The number of characters to copy
char content[size];
char line[size];
FILE *f1 = fopen(argv[1], "r"); // Read from first file
FILE *f2 = fopen(argv[2], "w"); // Write to second file
if (f1 == NULL || f2 == NULL) {
printf("\nThere was an error reading the file.\n");
exit(1);
}
while (fgets(content, size, f1) != NULL) {
// This is what I had first:
fprintf(f2, "%s", content);
// And when that didn't work, I tried this:
strncpy(line, content, size);
fprintf(f2, "%s", line);
}
fclose(f1);
fclose(f2);
return 0;
}
提前致谢!
答案 0 :(得分:1)
问题是fgets
的工作原理。它旨在读取下一行的结尾或最多size
个字符,以先到者为准。如果它在读取换行符之前读取size
个字符,则返回size
- 长度字符串,但它会在输入流中留下该行的其余部分,准备好在下一个{{1打电话!因此,如果fgets
为10,则您的循环只读取10个字符块中的长行,但仍然输出整行,每次10个字符。
如果你想保留当前程序的结构,那么诀窍就是使用size
来读取整行(使用比最长行更长的缓冲区和fgets
值),删除换行符(如果存在),将行截断为size
个字符(通过NUL终止,比如说),然后打印出缩短的行。
这是否足以提示,或者您只是想要一个有效的例子?
编辑:好的,这是一个有效的解决方案。
n