代碼: -按行讀取文件行成結構
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
const char s[3] = " "; /* trying to make 2 spaces as delimiter */
char *token;
char line[256];
fp = fopen ("input.txt","r");
fgets(line, sizeof(line), fp);
token = strtok(line, s);
/* walk through other tokens */
while(token != NULL)
{
printf(" %s\n", token);
token = strtok(NULL, s);
}
return 0;
}
input.txt的是象下面這樣:
01 Sun Oct 25 16:03:04 2015 john nice meeting you!
02 Sun Oct 26 12:05:00 2015 sam how are you?
03 Sun Oct 26 11:08:04 2015 pam where are you ?
04 Sun Oct 27 13:03:04 2015 mike good morning.
05 Sun Oct 29 15:03:07 2015 harry come here.
我想逐行讀取這個文件行並將其存儲在變量一樣
int no = 01
char message_date[40] = Sun Oct 27 13:03:04 2015
char friend[20] = mike
char message[120] = good morning.
如何實現這個? 是能夠通過行的文件線存儲到結構等
struct {
int no.;
char date[40];
char frined[20];
char message[120];
};
與上面的代碼我得到以下輸出: - (目前我讀爲簡單起見,僅一條線)
01
Sun
Oct
25
16:03:04
2015
john
nice
meeting
你!
你能後,你已經嘗試的代碼?這當然是可能的,並表明你已經做出了一些嘗試,幫助人們根據你當前的方法回答你的問題。 –
當然這是可能的!將數據讀入緩衝區,解析它以查找令牌邊界並存儲相應的項目。如果你想複製數據,那就這樣做。如果不是,則在每個條目結尾處將空值寫入緩衝區,並將指向每個條目開始的指針存儲在您的結構中。 –
我強烈建議你開始閱讀一本關於C的書。問題很簡單,顯然你不知道C.開始學習和編碼! –