【发布时间】:2014-02-06 20:05:46
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#define MAX_KEYS 26
#define MAX_UID 4
struct Key {
int keynum;
int id;
char cryptkeys[65];
};
int main(int argc, char ** argv) {
int MAX_LINE = 69;
struct Key *table = malloc(MAX_UID * sizeof(struct Key));
FILE *fileopen = fopen(filename, "r");
char *a[8];
int size = 0;
char *e;
char *string = NULL;
//reading the file
if(fileopen) {
while((e = fgets( line, MAX_LINE, fileopen )) != NULL) {
printf(e);
a[size] = strdup(e);
size++;
}
}
else {
printf("File does not exist\n");
exit(0);
}
for(int i = 0; i < size; i++ ) {
//printf("%s", a[i]); //no zero showing up
}
//parsing the id and the keys
char id[3];
char key[65];
int ids;
int idnum;
for(int i = 0; i < size-1; i++) {
struct Key *k = (struct Key*)malloc(sizeof(struct Key));
string = a[i];
//set the ID
for(int ix = 0; ix < 3; ix++) {
id[ix] = string[ix];
}
//printf("%s", id); No zero inbetween ID
//set the Keys
for(int j = 4; j < 68; j++) {
key[j-4] = string[j];
}
ids = strtol(string, &id2, 10);
//printf("Id is %d", ids); //zero shows up here
//printf(" ");
k->id = ids;
strcpy(k->cryptkeys, key);
k->keynum++;
table[i] = *k;
idnum++;
}
for(int i = 0; i < 5; i++) {
printf("%d", table[i].id);
printf(" ");
printf("%s", table[i].cryptkeys);
printf("\n");
}
return 0;
}
大家好,我正在尝试在指向我的结构的指针数组中进行结构操作。我可以很好地添加值,但我的行之间不断出现这个 0。我的文件只有三行长,后面是一个整数和一个字符串。一切似乎都正确解析,但我的文本中不断出现零。
如果您想知道,我的文件看起来像这样
421 0123456789abcdef0123456789abcde00123456789abcdef0123456789abcde0
422 00000000000000000000000000000000000000000000000000000000000000000
423 111111111111111111111111111111111111111111111111111111111111111
当我在我的表格中阅读后尝试打印输出时,它看起来像这样。
421 0123456789abcdef0123456789abcde00123456789abcdef0123456789abcde0
0
422 00000000000000000000000000000000000000000000000000000000000000000
0
423 111111111111111111111111111111111111111111111111111111111111111
我不认为它来自字符串的后面,因为每个键都是适当的长度。关于它可能来自什么的任何建议?任何帮助将不胜感激。
【问题讨论】:
-
我认为这不是你的问题,但是如果
e指向的字符串恰好包含任何%字符,则char *e; /* ... */ printf(e);具有潜在危险。使用printf("%s", e); -
您的代码甚至无法编译。
-
line中的fgets是什么? -
另外,现在,只需将
a声明为char a[8][MAX_LINE]并将table声明为struct Key table[MAX_UID]。避免strdup。我这样说是因为您的代码在 I/O(您遇到的问题)以及内存分配/释放方面存在一些问题。 -
谢谢Keith,我其实只是用它来测试和查找错误,我不打算再使用它了。为什么 strdup 不好用?