我们有一个赋值,即从文件中获取字符,将给定值向右移动(它在代码中有意义),然后将新值存储在新文件中,但我似乎遇到分段故障,据我所知,这意味着我试图访问我已经分配的内存之外的内存?我是C的新手,我设法调试此代码直到这一点,老实说,我不知道该去哪里。我甚至不太明白这个问题是什么。
#include<stdio.h>
//Get Shift amount
//Get ifilename
//Get ofilename
//open them
//Get characters one at a time from input
//Process and shift by shift amount
int main()
{
int i;//loop value
char a[62]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//Variable with every value
int sa = 0;//Store Shift value
char ofile[30];//contain the name of output file
char ifile[30];//contain name of input file
char value;//Value to keep the current value in
printf("How far in ascii values would you like to shift?\n");
scanf("%i", sa);//Get shift
printf("What is the name of your input file located in this directory?");
scanf("%s", ifile);//get input name
printf("What would you like to name your new file?\n Do note that it will overwrite the current file named this!");
scanf("%s", ofile);//Get output name
FILE *oIfile = fopen(ifile, "r"), *oOfile = fopen(ofile, "w");
while(value = fscanf(oIfile, "%c", value) != EOF)//Check to ensure that you never reach the end of the file
{
for(i=0; i<62; i++)//loop through the list of all characters
{
if(value == a[i])//check to see if the value from the input file matches with which letter
{
value = a[i+sa] % 62;//incrase the value by the shift amount, check if its longer than 62, add remainder
break;//break the for loop so we can restart the while loop with the next letter
}
}
fprintf(oOfile, "%c");//print the new value to the output file
}
fclose(oIfile);//close input file
fclose(oOfile);//close output file
}
由于我的scanf方法,是这个问题吗?
答案 0 :(得分:5)
除了将地址传递给你必须做的scanf
(scanf("%i",&sa)
之外(检查它的返回值也是正确的) - 你需要纠正一些事情: - < / p>
应该是(value = fscanf(oIfile, "%c", value)) != EOF
。 !=
的优先级高于=
,因此需要获得正确的结果。
同样a[(i+sa)%62]=...
是正确的做事方式。因为否则它将访问某些sa
值导致未定义行为的数组索引超出范围。
fprintf(stream,"%c",charvariable)
这将用于fprintf
。
value
覆盖了fscanf
返回的值返回的内容。您应该使用其他临时变量,或者甚至更好地使用此while(fscanf(oIfile, "%c", value)!=EOF)
。但要获得更多支票,你需要做点什么,比如
int c;
while((c=fscanf(oIfile, "%c", value))!=EOF)
通过在sa
中传递scanf
的值而非其地址,您在此处出现了细分错误。
答案 1 :(得分:1)
scanf
将地址作为参数。试试这个;
scanf("%i", &sa);//Get shift