我一直在尝试文件读写功能,遇到了分段错误。它似乎与从文件中读取有关。下面是我写的代码。
The code I wrote is given below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[]){
//char name[10];
//strcpy(name, "George");
//printf("%s\n", name);
//if(argc == 2){
//char *myname = "George";
FILE *file = fopen("Readmystuff" , "rt");//fopen(argv[1],"rt");
if(file == NULL)
printf("Could not open file: %s\n", strerror(errno));
char *str, *cr;
int maxsize = 200;
cr = fgets(str, maxsize, file);
int fcl = fclose(file);
printf("\n");
int strl = strlen(str);
if(fcl == 0)
printf("File closed succesfully\ncr: %c\nstr: %s\nTotal string size - 1 (for null): %i\n", *cr, str, strl);
else
printf("File did not close");
//}
//else
//printf("There must be one argument, argv[1] = the filename, for the code to work\n");
return 0;
}
char *str, *cr;
/* ... */
cr = fgets(str, maxsize, file);
您的
str
指针未初始化,其值不确定。您正在写入无效对象。要么定义一个足够大小的数组,要么使用 malloc
来分配一个。