我有一个包含大量“前景”的文件,所以每一行都有一个加密的姓氏、一个加密的名字、一个 12 位的 id 代码,然后是 4 个评级(3 个整数,1 个浮点数)。加密是通过文件中最后一个数字的值(发现是 310)来移动名称的每个字符。
尝试创建一个函数来解密 1 个字符,然后创建另一个函数来使用此函数解密字符串(名称),但出现错误和分段错误,请帮助!
#include <stdio.h>
#include <stdlib.h>
#define MSTRLEN 20
#define MAX_SIZE 1000
/* structure prototype */
typedef struct {
char lastname[MSTRLEN];
char firstname[MSTRLEN];
char secretcode[13];
int rank1;
int rank2;
float rank3;
int rank4;
} prospect_t;
int main (void)
{
FILE *ifile;
prospect_t *prospects;
char last[MSTRLEN],first[MSTRLEN],code[13],last_name,first_name;
int r1,r2,r4,num_prospects,shift,i,j;
float r3;
char unencrypt_letter(char *letter, int shift);
char unencrypt_name(char name[MSTRLEN], int shift);
/*finding how many prospects and last integer*/
ifile = fopen("prospects.txt","r");
num_prospects = 0;
if (ifile == NULL){
printf("File not found!\n");
return (-1);
}
while (fscanf(ifile,"%s %s %s %d %d %f %d",last,first,code,&r1,&r2,&r3,&r4)!=EOF){
num_prospects++;
}
shift = r4%26;
fclose(ifile);
/*--------------------------------------*/
/* dynamic memory allocation */
prospects = (prospect_t*)malloc(num_prospects*sizeof(prospect_t));
ifile = fopen("prospects.txt","r");
if (ifile == NULL){
printf("File not found!\n");
return (-1);
}
for(i=0;i<num_prospects;i++){
fscanf(ifile,"%s %s %s %d %d %f %d", prospects[i].lastname,prospects[i].firstname,prospects[i].secretcode,&prospects[i].rank1,&prospects[i].rank2,&prospects[i].rank3,&prospects[i].rank4);
}
/* to be used once get working
for(j=0;j<num_prospects;j++){
prospects[j].lastname = unencrypt_name(prospects[j].lastname,shift);
prospects[j].firstname = unencrypt_name(prospects[j].firstname,shift);
}
*/
/* to be taken out once working */
last_name = unencrypt_name(prospects[0].lastname,shift);
first_name = unencrypt_name(prospects[0].firstname,shift);
printf("%s %s\n",last_name,first_name);
fclose(ifile);
free(prospects);
return(0);
}
/* function to unencrypt one letter */
char unencrypt_letter(char *letter, int shift)
{
char *new_letter;
if ((*letter - shift) < 'a')
*new_letter = (char)((*letter - shift) + 26);
else
*new_letter = (char)(*letter - shift);
return(*new_letter);
}
/* function to unencrypt a name */
char unencrypt_name(char name[MSTRLEN],int shift)
{
char new_name[MSTRLEN];
int k;
k = 0;
while (name[k] != '\0'){
new_name[k] = unencrypt_letter(name[k],shift);
k++;
}
return(*new_name);
}
从终端,我得到以下信息:
la2.c:在函数'main'中: la2.c:68:2:警告:格式“%s”需要“char *”类型的参数,但参数 2 的类型为“int”[-Wformat] la2.c:68:2:警告:格式“%s”需要“char *”类型的参数,但参数 3 的类型为“int”[-Wformat] la2.c:在函数“unencrypt_name”中: la2.c:99:3:警告:传递 'unencrypt_letter' 的参数 1 使指针从整数而不进行强制转换 [默认启用] la2.c:79:6:注意:预期为 'char *' 但参数的类型为 'char'
** 链接阶段 gcc -o la2 la2.o
编译和链接成功完成 您的二进制文件可以通过键入以下命令运行:la2 engs20-1:~/engs20/workspace$ la2 Segmentation fault