[問題] fscanf

看板C_and_CPP (C/C++)作者 (HCO)時間15年前 (2009/02/19 21:33), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串1/2 (看更多)
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct data *ptr; struct data { char name[5]; int birth_year; int birth_month; int birth_day; char phone[10]; struct data *next; }; typedef struct data node; /*void print_data(ptr head) { while(head->next!=NULL) { printf("%-5s\t%-4d/%-2d/%-2d\t%-10s\n", head->name,head->birth_year,head->birth_month,head->birth_day, head->phone); head=head->next; } }*/ ptr Build_data(ptr head,char Build_name[5], int Build_birthyear,int Build_birthmonth,int Build_birthday,char Build_phone[10]) { ptr tmp=(ptr)malloc(sizeof(struct data)); strcpy(tmp->name,Build_name); tmp->birth_year=Build_birthyear; tmp->birth_month=Build_birthmonth; tmp->birth_day=Build_birthday; strcpy(tmp->phone,Build_phone); tmp->next=head; head=tmp; return head; } int main() { FILE *fp=fopen("input.txt","r+"); ptr start=NULL; char data_name[5]; int data_birth_year; int data_birth_month; int data_birth_day; char data_phone[10]; while(fscanf(fp,"%s\t%d\t%d\t%d\t%s",data_name, &data_birth_year,&data_birth_month,&data_birth_day,data_phone)!=EOF) { start=Build_data(start,data_name, data_birth_year,data_birth_month,data_birth_day,data_phone); } fprintf(fp,"\n%-5s\t%-10s\t%-10s\n","Name","Birthday","Phone"); while(start!=NULL) { fprintf(fp,"%-5s\t%-4d/%2d/%2d\t%-10s\n",start->name, start->birth_year,start->birth_month,start->birth_day,start->phone); start=start->next; } //print_data(fp); fclose(fp); system("pause"); return 0; } ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ input.txt Ken 1986 10 29 0928-123456 Mary 1988 1 30 04-25687755 Evan 1990 6 4 0937-845663 ---------------------------------------------- 我執行結果 Ken 1986 10 29 0928-123456 Mary 1988 1 30 04-25687755 Evan 1990 6 4 0937-845663 Name Birthday Phone Evan 1990/ 6/ 4 0937-845663 Mary 1988/ 1/30 04-25687755 Ken 1986/10/29 0928-123456 --------------------------------------------- 我想請問為什麼我fscanf資料出來了那最後fprintf還有原來資料?? 謝謝大大~~! -- ξ (  ̄ c ̄)y█████████████████████ξ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.169.48.51

02/19 21:55, , 1F
fscnaf完file offset停在file尾巴 你直接fprintf就append
02/19 21:55, 1F

02/19 22:10, , 2F
謝謝樓上 原來加個rewind就好了耶...
02/19 22:10, 2F

02/19 22:32, , 3F
若你寫入的資料量比原來的少 rewind後原本資料不會全覆蓋
02/19 22:32, 3F

02/19 22:33, , 4F
保險就fclose();fopen(xxx,"w");
02/19 22:33, 4F
文章代碼(AID): #19dL-k_Q (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #19dL-k_Q (C_and_CPP)