我试图用fscanf
一个结构中分配一个字符串, 我尝试这样做:如何使用fscanf或fgets动态分配结构中的字符串?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <Windows.h>
#include <string.h>
typedef struct _SPerson {
char *name;
char *surname;
char *id;
char *telephone;
}SPerson;
void main (void) {
unsigned int ne;
SPerson Archive[1000];
Load(Archive,&ne);
}
int Load(SPerson Archive[],unsigned int *ne) {
int k,i=0;
char s[4][20];
FILE *f;
f = fopen("archive.txt","r");
if(f==0) return 0;
while((k=fscanf(f,"%s %s %s %s",s[0],s[1],s[2],s[3]))==4) {
Archive[i].id = (char*) malloc(sizeof(char) *strlen(s[0]));
Archive[i].id =s[0];
Archive[i].name = (char*) malloc(sizeof(char) *strlen(s[1]));
Archive[i].name = s[1];
Archive[i].surname = (char*) malloc(sizeof(char) *strlen(s[2]));
Archive[i].surname = s[2];
Archive[i].telephone = (char*) malloc(sizeof(char) *strlen(s[3]));
Archive[i].telephone =s[3];
i++;
}
*ne = i;
fclose(f);
return 1;
}
也许在我的脑子它是正确的,但在加载数据出现了问题,所以这是正确的,并清除方法来动态读取字符串? 我以为使用fgets
,但我的字符串被一个空格分开,所以我需要实现另一个功能,拆分。谁能帮我?
千万不要使用'scanf'函数,它们按设计破坏。你想'fgets' +'strtok' +'strdup'。另外,根据定义,'sizeof(char)'是1 *,所以不要写它。 – zwol
你有任何错误或警告? ?? –
显示输入文件分隔方式的示例将有所帮助。只需几行,如果所有行都包含相同的字段集合。 – ryyker