[英]How to read text from a .txt file and then store it in a record (data structure)?
[英]how data can be read from a text file and stored as as a structure?
我們將此文件稱為f1.txt,它具有給定的屬性。
並從另一個文件中調用駐留結構f2.txt,它將讀取以下屬性
然后將通過鍵盤詢問居留權。
我試圖在某個時候被卡住
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int student_code;
char name[20];
char ID[20];
};
int main()
{
FILE *input_file;
struct student input;
input_file = fopen("f1.txt", "r");
if(input_file == NULL)
{
fprintf(stderr, "\nError!\n");
exit(1);
}
while(fread(&input, sizeof(struct student), 1, input_file))
printf("student code = %d name = %s ID = %s", input.student_code,
input.name, input.ID);
fclose(input_file);
return 0;
}
我是C編程的新手
例如f1.txt文件將采用以下格式
f1.txt
123456 yourname 987654
564566 test 454545
使用fscanf
讀取行,因為您知道格式
將值存儲到臨時變量中
將它們復制到適當的數據結構中:如果您不知道學生人數,則使用動態數組或列表。
編輯:數組允許隨機訪問,另一方面,列表僅允許順序訪問。 這是我嘗試使用列表的方法:
typedef struct student
{
int student_code;
char name[20];
char ID[20];
struct student* next;
}student_t;
typedef struct list_s
{
int size;
student_t* head;
student_t* tail;
} list_t;
void list_push_back(list_t* l, int code, char n[20], char id[20])
{
student_t* tmp = (student_t*)calloc(1,sizeof(*tmp));
tmp->student_code = code;
strncpy(tmp->name, n, 20);
strncpy(tmp->ID, id, 20);
if (l->head == NULL)
{
l->head = tmp;
l->tail = tmp;
l->size++;
return;
}
l->tail->next = tmp;
l->size++;
}
void list_print(list_t* l)
{
student_t* it = l->head;
while (it)
{
fprintf(stdout, "%d %s %s\n", it->student_code, it->name, it->ID);
it = it->next;
}
}
int main(int argc, char* argv[])
{
FILE *input_file;
struct student input;
input_file = fopen("f1.txt", "r");
if (input_file == NULL)
{
fprintf(stderr, "\nError!\n");
exit(1);
}
list_t* list = (list_t*)calloc(1,sizeof(*list));
char tmp_name[20];
char tmp_id[20];
int tmp_code = 0;
while (fscanf(input_file, "%d %s %s", &tmp_code, tmp_name, tmp_id) != EOF)
{
list_push_back(list, tmp_code, tmp_name, tmp_id);
}
fclose(input_file);
list_print(list);
return 0;
}
要將單個記錄讀入結構input
:
fscanf( input_file, "%d %s %s", &input.student_code, input.name, input.ID )
將一個整數和兩個字符串讀入相關成員。
fscanf()
返回成功分配的格式化字段的數量,以便以您的代碼嘗試的方式顯示文件中的所有記錄:
while( fscanf( input_file, "%d %s %s", &input.student_code,
input.name,
input.ID ) == 3 )
{
printf( "student code = %d, name = %s, ID = %s\n", input.student_code,
input.name,
input.ID ) ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.