2015-10-27 57 views
0

代碼: -按行讀取文件行成結構

#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 

你!

+0

你能後,你已經嘗試的代碼?這當然是可能的,並表明你已經做出了一些嘗試,幫助人們根據你當前的方法回答你的問題。 –

+0

當然這是可能的!將數據讀入緩衝區,解析它以查找令牌邊界並存儲相應的項目。如果你想複製數據,那就這樣做。如果不是,則在每個條目結尾處將空值寫入緩衝區,並將指向每個條目開始的指針存儲在您的結構中。 –

+2

我強烈建議你開始閱讀一本關於C的書。問題很簡單,顯然你不知道C.開始學習和編碼! –

回答

0

一種方法是使用fgets()來讀取文件的每一行和sscanf()來解析每一行。掃描集%24[^\n]將最多讀取停止在換行符上的24個字符。日期格式有24個字符,所以它讀取日期。掃描集%119[^\n]最多可讀取119個字符,以防止將太多字符寫入message並停在換行符上。 sscanf()返回已成功掃描的字段數,因此4表示已成功掃描線。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

struct Text { 
    int no; 
    char date[40]; 
    char name[20]; 
    char message[120]; 
}; 

int main() 
{ 
    char line[200]; 
    struct Text text = {0,"","",""}; 

    FILE *pf = NULL; 

    if ((pf = fopen ("input.txt", "r")) == NULL) { 
     printf ("could not open file\n"); 
     return 1; 
    } 
    while ((fgets (line, sizeof (line), pf))) { 
     if ((sscanf (line, "%d %24[^\n] %19s %119[^\n]" 
     , &text.no, text.date, text.name, text.message)) == 4) { 
      printf ("%d\n%s\n%s\n%s\n", text.no, text.date, text.name, text.message); 

     } 
    } 
    fclose (pf); 
    return 0; 
} 
0

使用strstr,而不是strtok象下面這樣:

#include <stdio.h> 
#include <string.h> 

int main (void){ 
    FILE *fp; 
    const char s[3] = " "; /* trying to make 2 spaces as delimiter */ 
    char *token, *end; 
    char line[256]; 

    fp = fopen ("input.txt","r"); 
    fgets(line, sizeof(line), fp); 
    if(end = strchr(line, '\n')) 
     *end = '\0';//remove newline 
    fclose(fp); 

    token = line; 
    while(token != NULL){ 
     if(end = strstr(token, s)) 
      *end = '\0'; 
     printf("'%s'\n", token); 
     if(end != NULL) 
      token = end + 2;//two space length shift 
     else 
      token = NULL; 
    } 
    return 0; 
}