我有一個結構藝術。我想創建一個函式來將 txt 檔案讀入指向結構的指標向量。
struct art {
char *author;
char *title;
};
typedef struct art Art;
Art *readFile(Art **vec, FILE* file);
int main(void){
FILE *file = fopen("filename.txt","r");
if (file==NULL){
printf("Failed");
return NULL;
}
Art **vec = (Art**)malloc(150*sizeof(Art*));
vec = readFile(vec,file);
return 0;
}
Art *readFile(Art **vec, FILE* file){
// I want to allocate memory for each of the strings, they have to be of size 80.
while(fscanf(file, "%[^;];%[^;];", x, y) ==2); //the author and title are separated by semicolons in the file
return vec;
}
我應該在 x 和 y 值中輸入什么???
uj5u.com熱心網友回復:
如果您知道它們不超過 80 個字符,請使用本地陣列:char x[81], y[81];然后您可以在結構中使用strdup或復制它們malloc strcpy。
struct art {
char *author;
char *title;
};
typedef struct art Art;
int readFile(Art **vec, int array_length, FILE* file);
int main(void) {
FILE *file = fopen("filename.txt","r");
if (file==NULL){
printf("Failed");
return NULL;
}
Art **vec = malloc(150 * sizeof(Art *));
int num_read = readFile(vec, 150, file);
return 0;
}
int readFile(Art **vec, int array_length, FILE* file)
{
int count = 0;
char author[81], title[81];
while (fscanf(file, "
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359884.html
上一篇:在PyGetSetDef中使用閉包來重用屬性getter-settter
下一篇:為什么我的代碼沒有輸入地址?
