c 从文件中读取并获取两个字符之间的字符串
c read from file and get string between two characters
我有一个文本文件 chat.txt 这种变体:
[23.05.2013 20:10:05] [imo.skype] NibbleByte: Hello
[23.05.2014 20:10:05] [imo65.skype] NibbleBdsfyte: Hesdf :)
[23.05.2015 20:10:05] [imo69.skypeeee] NibbledsfByte: How are you?
我尝试读取文件和 susbstring 日期、客户端 (imo)、协议、用户名和消息。
例如:
date: 23.05.2013 20:10:05
client: imo
protocol: skype
username: NibbleByte
message: Hello
在此之后我必须将它放入链表中,但我的问题是如何读取它。有任何想法吗?谢谢
这使用扫描集来解析行。
扫描集 %29[^]]
最多扫描 29 个非 ]
.
的字符
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *pf = NULL;
char line[500] = {0};
char date[30] = {0};
char client[30] = {0};
char protocol[30] = {0};
char username[30] = {0};
char message[300] = {0};
if ( ( pf = fopen ( "chat.txt", "r")) == NULL) {
printf ( " could not open file\n");
return 1;
}
while ( fgets ( line, sizeof ( line), pf)) {
if ( ( sscanf ( line," [%29[^]]] [%29[^.].%29[^]]] %29[^:]: %299[^\n]%*c"
, date
, client
, protocol
, username
, message)) == 5) {
printf ( "date : %s\n", date);
printf ( "client : %s\n", client);
printf ( "protocol : %s\n", protocol);
printf ( "username : %s\n", username);
printf ( "message : %s\n", message);
}
}
return 0;
}
我有一个文本文件 chat.txt 这种变体:
[23.05.2013 20:10:05] [imo.skype] NibbleByte: Hello
[23.05.2014 20:10:05] [imo65.skype] NibbleBdsfyte: Hesdf :)
[23.05.2015 20:10:05] [imo69.skypeeee] NibbledsfByte: How are you?
我尝试读取文件和 susbstring 日期、客户端 (imo)、协议、用户名和消息。
例如:
date: 23.05.2013 20:10:05
client: imo
protocol: skype
username: NibbleByte
message: Hello
在此之后我必须将它放入链表中,但我的问题是如何读取它。有任何想法吗?谢谢
这使用扫描集来解析行。
扫描集 %29[^]]
最多扫描 29 个非 ]
.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *pf = NULL;
char line[500] = {0};
char date[30] = {0};
char client[30] = {0};
char protocol[30] = {0};
char username[30] = {0};
char message[300] = {0};
if ( ( pf = fopen ( "chat.txt", "r")) == NULL) {
printf ( " could not open file\n");
return 1;
}
while ( fgets ( line, sizeof ( line), pf)) {
if ( ( sscanf ( line," [%29[^]]] [%29[^.].%29[^]]] %29[^:]: %299[^\n]%*c"
, date
, client
, protocol
, username
, message)) == 5) {
printf ( "date : %s\n", date);
printf ( "client : %s\n", client);
printf ( "protocol : %s\n", protocol);
printf ( "username : %s\n", username);
printf ( "message : %s\n", message);
}
}
return 0;
}