[英]Reading/Writing to file array of structure in C
嗨,我正在嘗試寫入結構的 txt 文件數組,然后將其加載回來。 這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEXT_LEN 100
struct Data_s
{
char name[TEXT_LEN];
char brand[TEXT_LEN];
char invNr[TEXT_LEN];
long year;
};
long saveDB(struct Data_s* items, long len, char* outputFile);
long loadDB(struct Data_s* items, long len, char* inputFile);
int main()
{
struct Data_s std[2];
struct Data_s* ptr;
int i;
ptr = std;
strcpy(ptr->name, "cat");
strcpy(ptr->brand, "catTest");
strcpy(ptr->invNr, "123456");
ptr->year = 2000;
ptr++;
strcpy(ptr->name, "lion");
strcpy(ptr->brand, "lionTest");
strcpy(ptr->invNr, "100000");
ptr->year = 2020;
ptr = std;
saveDB(ptr, 2, "try.txt");
loadDB(ptr, 2, "try.txt");
}
long saveDB(struct Data_s* items, long len, char* outputFile)
{
FILE* fpOut;
if ((fpOut = fopen(outputFile, "w")) == NULL)
{
printf("Unable to open file - quitting\n");
return -1;
}
int i;
// fprintf(fpOut,"name brand invNr year \n");
for (i = 0; i < len; i++)
{
fprintf(fpOut, "%s %s %s %li \n", items->name, items->brand, items->invNr, items->year);
items++;
}
fclose(fpOut);
return 0;
}
long loadDB(struct Data_s* items, long len, char* inputFile)
{
char* num[100];
FILE* fptr;
if ((fptr = fopen(inputFile, "r")) == NULL)
{
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
return 1;
}
fscanf(fptr, "%s", *num);
printf("Value of n=%s", *num);
fclose(fptr);
return 0;
}
它正在正確寫入文件,並且當程序開始從文件中讀取時出現分段錯誤。
任何人都有想法幫助我正確地編寫這個並從文件讀回結構?
謝謝
在ptr++
之后,您的ptr
指向第二個元素。 在您的saveDB
function中,您正試圖在最后一個元素之后寫入一個。
您應該將std
的第一個元素的地址傳遞給您的saveDB
和loadDB
函數。
一種閱讀方式是:
long loadDB(struct Data_s *items,long len,char *inputFile)
{
int i = 0;
FILE *fptr;
if ((fptr = fopen(inputFile,"r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
return 1;
}
for (i = 0; i < len; ++i) {
fscanf(fptr, "%s %s %s %li", items->name, items->brand, items->invNr, &items->year);
items++;
}
fclose(fptr);
return 0;
}
在您的main
function 中,您可以像這樣打印值:
printf("Name=%s\n", ptr->name);
printf("Brand=%s\n", ptr->brand);
printf("invNr=%s\n", ptr->invNr);
printf("year=%ld\n", ptr->year);
ptr++;
printf("Name=%s\n", ptr->name);
printf("Brand=%s\n", ptr->brand);
printf("invNr=%s\n", ptr->invNr);
printf("year=%ld\n", ptr->year);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.