这是代码。 我不知道如何解决这个问题。 该程序是关于 I/O 文件并将每一行从十六进制转换为二进制。 我得到了第一个正确的结果,然后是段错误。 谁能指出这有什么问题吗 谢谢
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *file, *newFile;
char output[13];
int main(int argc, char* argv[]){
file = fopen(argv[1],"r");
newFile = fopen("output.txt","wa+");
char binary1[50];
char first[2], secondDigit[2], third[2], last[2];
char scr[5];
char binary[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101","0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110","1111"};
char digits [] = "0123456789abcdef";
while(fgets(scr, 5, file) && scr[5] != EOF) {
char res[100];
int p = 0;
int value =0;
while(scr[p])
{
const char * v = strchr(digits, tolower(scr[p]));
if(v[0]>96){
value=v[0]-87;
}
else{
value=v[0]-48;
}
if (v){
strcat(res, binary[value]);
}
p++;
}
printf("Res:%s\n", res);
}
fclose(newFile);
fclose(file);
return 0;
}
最佳答案
问题是当您到达行尾时 scr[p]
是 \n
并且 char *strchr(const char * s, int c);
的特点是,当在字符串 s
中没有找到 c
的出现时,它会返回 NULL
.
段错误是因为当您尝试取消引用时 v
为 NULL
。
您应该检查 v
何时为 NULL
并进行相应处理。
执行 file = fopen(argv[1],"r");
时这也是一个问题,如果文件不存在,则变量 file
将为 NULL
,在调用 fgets(scr, 5, file)
时导致段错误。
关于c语言段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44253724/