【发布时间】:2020-12-20 10:34:40
【问题描述】:
请有人告诉我为什么我经常得到 coredump 分段? 当我选择 n=1 时工作正常但问题是 n=2 和 n=3 但我不知道为什么。我想读取一个文本文件并返回一个文本、二进制或十六进制文件。
我编辑了代码并编译它,我只收到一个警告,它指的是 %x,但我不关心它,因为首先我必须解决 n==2。现在我没有 coredump 错误。似乎没有错误,但我的第二个文件是空的。
int main(int argc, char *argv[])
{
if (argc != 3){
printf("Use this scheme: ./executabel read_file write_file -option(-b,-t,-x)\n");
exit(EXIT_FAILURE);
}
int fd1=open(argv[1], O_RDONLY);
int fd2=open(argv[2], O_WRONLY | O_CREAT);
char buffer[1024];
int rd_count = 0;
int wr_count = 0;
int n;
FILE * fpw;
fpw = fdopen (fd2, "w");
if (fd1 == -1){
printf("Failed to open the read-file.\n");
exit(EXIT_FAILURE);
}
if (fd2 == -1){
printf("Failed to open the write-file.\n");
exit(EXIT_FAILURE);
}
printf("Please choose one:\n");
printf("1. –t forces the output file to be a text one.\n");
printf("2. –b forces the output file to be binary.\n");
printf("3. –x forces the output file to be a hexadecimal representation.\n");
scanf("%d", &n);
while ((rd_count = read(fd1, (void*) buffer, 1024)) > 0){
int bytes_wr = 0;
while (bytes_wr != rd_count){
if (n==1){
wr_count = write(fd2, (void*) (buffer+bytes_wr), rd_count-bytes_wr);
}else if (n==2){
wr_count = fwrite( (void*) (buffer+bytes_wr), sizeof(float), rd_count-bytes_wr, fpw);
}else{
fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
}
if (wr_count < 0) {
perror("Failed to write to file");
exit(EXIT_FAILURE);
} else {
bytes_wr += wr_count;
}
}
}
if (rd_count < 0) {
perror("Failed to read from file");
exit(EXIT_FAILURE);
}
close(fd1);
close(fd2);
chmod(argv[2],777);
exit(EXIT_SUCCESS);
}
顺便说一句,这是警告
mahsa@mahsa-G53SW:~$ gcc -o ex4.o ex4.c -Wall -Wextra
ex4.c: In function ‘main’:
ex4.c:55:23: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘void *’ [-Wformat=]
55 | fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
| ~^ ~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | void *
| unsigned int
| %p
我改变了这一行
fprintf(fpw,"%x",(void*) (buffer+bytes_wr));
到这里
fprintf(fpw,"%02x",buffer[bytes_wr]);
现在我什至没有警告。似乎一切正常,但是当我打开第二个文件时是空的。
【问题讨论】:
-
万一
n==2你将通过fwrite写入多少字节?这些字节存储在哪里?您在该位置允许访问多少字节? -
与段错误无关:除了第一个字节之外的十六进制转换在哪里?此外,
main的返回类型是int,而不是void,除非您处于独立环境中。 -
另外请解释一下:如果输入是文本文件,你期望的二进制文件输出是什么?
-
wr_count = fwrite( (void*) (buffer+bytes_wr), sizeof(float), rd_count-bytes_wr, fd2);检查这部分。我想从缓冲区中读取并写入所有内容。在缓冲区中最大可以是 1024。 -
我刚刚注意到您更改了问题。在给出 cmets 和答案后,请不要更改您的代码。这将使其中一部分无效并使未来的读者对您的问题感到困惑。如果根据cmets适配的话,可以加到你的问题中,但不要去掉错误的代码。