[英]Reading a file into a C program
我的程序讀取文件,相應地顯示它,但是當再次嘗試查看內容時,它們消失了。
結構:
typedef struct friends_contact {
char *First_Name;
char *Last_Name;
char *home;
char *cell;
} fr;
主要的:
int main() {
fr friends[5];
char buffer[BUFFSIZE];
int counter = 0;
int i = 0;
menu(friends, &counter, i, buffer);
getch();
return 0;
}
用於打開文件的菜單函數中的if語句:
if (user_entry1 == 1) {
printf("Please enter a file name");
scanf("%s", user_entry3);
read = fopen(user_entry3, "r");
}
If 語句允許用戶選擇查看通訊錄的聯系人。
if (user_entry == 4 ) {
print_contact(friends, counter, i, user_entry3);
if (user_entry1 == 1) {
file2(friends, counter, i, buffer, read);
}
}
讀取功能:
char file2(fr *friends, int *counter, int i, char buffer[], FILE *read) {
while (fscanf(read, "%s", buffer) != EOF) {
friends[i].First_Name = malloc(BUFFSIZE * strlen(buffer));
strcpy(friends[i].First_Name, buffer);
return printf("\n""%s ", friends[i].First_Name);
}
fclose(read);
}
如果您需要我提供更多代碼。 我試圖讓它將文件中的內容讀入聯系人列表,以便我可以查看、搜索或刪除它們。
PS 我知道其他一些代碼可能並不完美,但現在我只是擔心弄清楚這一點:)。
file2
函數將文件的每一行讀取到friends[i]
但從不增加i
。 因此,每個新記錄都會覆蓋前一個記錄……除了該函數在循環的第一次迭代期間返回。 在這種情況下,使用if
比使用while
更好。
其他建議:
而不是使用}else;
你可以用}
關閉if
塊。 一個if
不需要else
。
而不是成語
if (foo == 1) {
// do stuff
} else if (foo == 2) {
// do other stuff
} else {
// do default stuff
}
您可以使用
switch (foo) {
case 1:
// do stuff
break;
case 2:
// do other stuff
break;
default:
// do default stuff
}
代替
printf("\n""%s ",friends[i].First_Name);
使用單個字符串更常見,末尾有換行符:
printf("%s\n", friends[i].First_Name);
您必須再次使用fseek
將文件指針重置到文件的開頭。 你的讀取函數應該像這樣開始:
fseek(read, 0, SEEK_SET); // set file pointer to the beginning of the file
您不應該忘記測試文件是否可以打開:
if ( user_entry1==1 ){
printf( "Please enter a file name" );
scanf( "%s", user_entry3 );
if ( ( read = fopen( user_entry3, "r" ) ) != NULL ){
printf( "The file couldn't be opened" );
}
else{
.
.
.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.