按行读取文件行成结构

问题描述:

代码: -按行读取文件行成结构

#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.开始学习和编码! –

一种方法是使用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; 
} 

使用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; 
}