【发布时间】:2019-12-30 21:27:56
【问题描述】:
我正在尝试解决这个关于在 C 中将数据从一个文件移动到另一个文件的问题。运行该程序会给出一个segmentation error 11。我附上了问题的图片。 Exercise 4
我相信打开文件有问题,我在终端里面输入了C代码脚本名称:code.c file1.txt file2.bin -b。文件包含在路径中。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char** argv){
size_t k;
char read1[100] = {};
FILE* s;
FILE* d;
if (argc < 4) {
printf("NA");
exit(1);
}
if (strcmp(argv[4], "-b") == 0) {
printf("binary file output\n");
d = fopen(argv[3], "wb");
if (d == NULL) {
printf("cant open d");
exit(1);
}
} else {
if (strcmp(argv[4], "-t") == 0) {
printf("textual file output\n");
d = fopen(argv[3], "w");
} else {
printf("error");
exit(1);
}
}
s = fopen(argv[2], "r");
if (s == NULL) {
printf("cant open s");
exit(2);
}
k = fread(read1, sizeof(char),100, s);
while (k != 0) {
fwrite(read1, k,1, s);
k = fread(read1, sizeof(char),100, s);
}
fwrite(read1, k,1, s);
fclose(s);
fclose(d);
return 1;
}
我希望将所有数据从file 1 移动到file 2,并且file2 output 可以是二进制或文本,具体取决于用户输入流。忽略了“十六进制”大小写。
【问题讨论】:
-
请不要张贴文字图片。将文本复制到问题中,这对屏幕阅读器更友好,可以轻松复制粘贴和执行差异,并且占用更少的空间。谢谢。
-
在使用
argv[4]之前,请检查argc。在您使用fread之前,请检查fopen是否返回了一个有效的指针。如果没有这些检查,您可能会遇到无法检测到的故障。另外:将变量read命名为与库函数相同是不明智的。 -
如上所述,您还需要存储来自
fread的返回值并在fwrite中使用它。另外,请参阅Why iswhile ( !feof (file) )always wrong? 循环应该由来自fread的返回值驱动。此外,您应该将第二个和第三个参数反转为fread和fwrite:size和count。 -
您没有更改
fwrite,并且,在循环之后不应该有任何fwrite。请小心。另外:sizeof (char)定义为1。
标签: c file segmentation-fault