当前位置: 技术问答>linux和unix
求助,gcc下编译下面代码出现 段错误
来源: 互联网 发布时间:2016-11-20
本文导语: #include #include #include #define once 1024 //即一次读1024个字节,如果存在那么多 int main(int agc,char *agv[]) { FILE *from,*to; long whole_size,n,i; int read_byte,write_byte,buffer[once]; if(agc != 3) { printf("please input source file and targe...
#include
#include
#include
#define once 1024 //即一次读1024个字节,如果存在那么多
int main(int agc,char *agv[])
{
FILE *from,*to;
long whole_size,n,i;
int read_byte,write_byte,buffer[once];
if(agc != 3)
{
printf("please input source file and target filen");
return(0);
}
if((from = fopen(agv[1],"r"))== NULL)
{
printf("can not open filen");
return(0);
}
if((to = fopen(agv[2],"wt+") )== NULL)
{
printf("can not open and creat the targetn");
exit(1);
return(0);
}
//调回文件尾
if((fseek(from,0L,SEEK_END)) != 0)
{
printf("couldn't measure the file's!n");
exit(1);
return(0);
}
if((whole_size = ftell(from)) != -1)//计算文件总大小,按字节计算
{
printf("the file's size is %d KBn",(whole_size / 1024));
}
else
{
printf("seek erron");
exit(1);
}
if((fseek(from,0,SEEK_SET)) == -1) //调回文件头 段错误出现在这,只要不要语句就行
{
printf("seek erro!n");
exit(1);
}
n = whole_size / once;
if(n >= once)
{
for(i = 0;i = once)
读出的语句
read_byte = fread(buffer,sizeof(char),whole_size,from);
指定的字节数是whole_size
比如文件长度为4096字节 n = while_size / once = 4096 / 1024 = 4
read_byte = fread(buffer,sizeof(char),whole_size,from);
将会被执行,不出错才怪。
#include
#include
#define once 1024 //即一次读1024个字节,如果存在那么多
int main(int agc,char *agv[])
{
FILE *from,*to;
long whole_size,n,i;
int read_byte,write_byte,buffer[once];
if(agc != 3)
{
printf("please input source file and target filen");
return(0);
}
if((from = fopen(agv[1],"r"))== NULL)
{
printf("can not open filen");
return(0);
}
if((to = fopen(agv[2],"wt+") )== NULL)
{
printf("can not open and creat the targetn");
exit(1);
return(0);
}
//调回文件尾
if((fseek(from,0L,SEEK_END)) != 0)
{
printf("couldn't measure the file's!n");
exit(1);
return(0);
}
if((whole_size = ftell(from)) != -1)//计算文件总大小,按字节计算
{
printf("the file's size is %d KBn",(whole_size / 1024));
}
else
{
printf("seek erron");
exit(1);
}
if((fseek(from,0,SEEK_SET)) == -1) //调回文件头 段错误出现在这,只要不要语句就行
{
printf("seek erro!n");
exit(1);
}
n = whole_size / once;
if(n >= once)
{
for(i = 0;i = once)
读出的语句
read_byte = fread(buffer,sizeof(char),whole_size,from);
指定的字节数是whole_size
比如文件长度为4096字节 n = while_size / once = 4096 / 1024 = 4
read_byte = fread(buffer,sizeof(char),whole_size,from);
将会被执行,不出错才怪。
|
数组越界的结果是不确定的,出现什么状况都有可能,不必太深究为什么,尽量不要越界才是最重要的。