【发布时间】:2019-03-27 01:13:12
【问题描述】:
晚上好!我现在的目标是做一些小的东西来读出任何类型文件中的字符(并将它们放入一个字符串中以供程序稍后使用)但我目前一直遇到一个问题,当我运行代码和它时“input[n] = (char)c;”行的分段错误并且我尝试通过打印字符和 n 的值来进行故障排除,并且每次(尽管我将 malloc 更改为不同的大小)printf 语句都会在数字“134510”的一半处打印,或者会在之前的偏移量 134509 处打印字符故障在下面的行。我想知道我的问题是什么以及如何解决它,因为我很奇怪该程序只能通过大约 10% 的文件。
谢谢!!
int c = 0; //Counting the current character being read
int n = 0; //Counting the current character being written
char *input; //A string of all characters in the file
FILE *inputFile; //File to read
if(!(inputFile = fopen(argv[1],"r"))){ // Open in read mode
printf("Could not open file"); // Print and exit if file open error
return 1;
}
input = (char *)malloc(sizeof(inputFile) * sizeof(char));
while (1){ //Put all of the characters from the file into the string
c = fgetc(inputFile);
if(feof(inputFile)){ //If it reaches the end of the file, break the loop
break;
}
printf("%c ", c); //Troubleshooting
input[n] = (char)c;
n++;
}
【问题讨论】:
标签: c string segmentation-fault