读书人

为什么会有分段异常

发布时间: 2013-04-09 16:45:09 作者: rapoo

为什么会有分段错误
#include<stdio.h>

#define CORRECT 0
#define FILE_OPEN_ERROR 1
#define INPUT_ERROR 2
#define N 100

int main()
{
int i; char m; char a[N];
FILE *fp;
fp =fopen("data.ina',"r");
if(fp ==NULL){
fprintf(stderr,"can't open the file!\n");
fclose(fp);
return 1;
}
if(fscanf(fp,"%c",&a[i])!=1){
fprintf(stderr,"error\n");
fclose(fp);
return 2;
}
fscanf(fp,"%c",&a[i]);
for(i=0;i<100;i++){
if(a[i]<=90 && a[i]>=65)
printf("%c",a[i]);
if(a[i]<=122 && a[i]>=97){
m=a[i]-32;
printf("%c",m);
}
return 0;
fclose(fp);
}
}
这是将data.in的字符输出,若大写则直接输出,若是小写则换为大写在输出。如AbCd则输出为ABCD
请问老师们,为什么我的代码没有报错,到运行时却出现分段错误?还请老师给予解释。谢谢
[解决办法]


if(fp ==NULL){
fprintf(stderr,"can't open the file!\n");
fclose(fp);
return 1;
}

这里打开失败时、不能关闭文件否则段错误、另外scanf不能以%c读取(%s\%d才可以)
你这个可以先把字符全部读取到数组里面再转.
printf("%c",m);
}
return 0;


fclose(fp);
}这里关闭文件怎么是在return 0 之后呢! 肯定不行。。return 程序都退出了



#include<stdio.h>

#define CORRECT 0
#define FILE_OPEN_ERROR 1
#define INPUT_ERROR 2
#define N 100

int main()
{
int i; char m; char a[N];
FILE *fp;
fp = fopen("data.ina","r");
if(fp==NULL){
fprintf(stderr,"can't open the file!\n");
//fclose(fp); 打开失败不能关闭
return 1;
}
fscanf(fp,"%s",a);

for(i=0;i<100;i++){
if(a[i]<=90 && a[i]>=65)
printf("%c",a[i]);
if(a[i]<=122 && a[i]>=97){
m=a[i]-32;
printf("%c",m);
}
//return 0;
fclose(fp);
}
getchar();
}

读书人网 >C语言

热点推荐