【问题标题】:c read from file and get string between two charactersc 从文件中读取并获取两个字符之间的字符串
【发布时间】:2015-05-25 11:53:45
【问题描述】:

我在这个变体中有一个文本文件 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?

我尝试读取文件和子字符串日期、客户端(imo)、协议、用户名和消息。

例如:

date: 23.05.2013 20:10:05

client: imo

protocol: skype

username: NibbleByte

message: Hello

在此之后,我必须将其放入链表中,但我的问题是如何阅读它。有任何想法吗?谢谢

【问题讨论】:

  • 你能证明你尝试过的任何东西吗?
  • 我尝试这样的事情 - goo.gl/RECj17 。在单词开始和结束时制作标志..但我不确定我的方法是否正确

标签: c file substring


【解决方案1】:

这使用扫描集来解析行。
扫描集 %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;
}

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2022-12-13
    • 1970-01-01
    • 2012-12-28
    相关资源
    最近更新 更多