代码: -
#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)
一种方法是使用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;
}
答案 1 :(得分: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;
}