【问题标题】:How to copy part of text file into a string in C?如何将部分文本文件复制到C中的字符串中?
【发布时间】:2016-04-30 11:51:04
【问题描述】:

我有一个文本文件:

recipName=叉子朋友=Cup sonName=Spork feature=hair sendName=Spoon"

我想要做的是将 = 符号之前的所有单词复制到一个字符数组,并将 = 右侧的内容复制到另一个字符数组或字符串。

这是我目前的代码:

int main (int argc, char * argv[]) 
{
    char data[100];
    char line[5][100];
    char key[5][100];
    char value[5][100];   

    FILE * fdata = fopen(argv[1], "r"); //read data.txt file
    FILE * ftemp = fopen(argv[2], "r"); //read and write to template.txt file

    if (fdata == NULL) 
    {
        printf("could not read file.\n");
    }

    int i = 0;
    while (fgets(data, 100, fdata) != NULL) 
    {
        printf("data: %s", data);
        //this is where i get stuck, idk how to utilize this loop to copy the variable and variable names from the data.txt file i was given...thanks for the help

        ++i;
    }

    fclose(fdata);
    fclose(ftemp);

    return 0;
}

【问题讨论】:

  • data 是char 的数组,因此(可能是嵌套的)循环可用于按顺序检查和复制单个字符。另外,请查看标准头文件<string.h> 中的函数文档,例如strtok()。鉴于您在阅读数据后显示的代码完全为零,因此我怀疑很多人会提供更多细节。
  • 在阅读帮助中心关于为 SO 写好问题的信息时,有一个大意为:“SO 是为了解决问题,而不是获得帮助”。此时您正在寻求帮助。
  • 你可能需要一个结构体。

标签: c string file io


【解决方案1】:

为 chqrlie

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

    # define MAX 5

    int Count_Token ( char str[], char token )
    {
        char *p;
        int cnt = 0;

        /* str must be null terminated with '\0' otherwise infinite loop will happen */

        p = str;
        while ( *p != '\0' )
        {
            if ( *p == token )
                cnt++;

            p++;
        }

        return cnt;
    }


    void Get_KeyValue_at_Position( char str[], char token, int position, char k[], char v[] )
    {
        char *ptr;
        char temp_str[100];
        int i;

        ptr = str;

        /* assumes str[] passed in does not have leading space before first key */

        /* this for loop puts ptr on start of key at position */
        for ( i = 0; i < position; i++ }
        {
            /* move ptr to next space */
            while (( *ptr != ' ' ) && ( *ptr != '\0' ))
                ptr++;

            /* account for more than one space separating key/value pairs and put ptr on beginning of next key */
            while ( *ptr == ' ' )
                ptr++;
        }

        /* get key */
        strcpy( temp_str, ptr )
        ptr_token = strchr( temp_str, token );
        *ptr_token = '\0';
        strcpy( k, tempstr );

        /* get value */
        strcpy( temp_str, ptr );
        ptr_token = strchr( temp_str, token );
        ptr_token++;
        strcpy( v, ptr_token );
    }


int main ( int argc, char * argv[] ) 
{
    char data[100];
    char key[MAX][100];     /* has string before token */
    char value[MAX][100];   /* has string afte token */

    FILE *fdata;

    fdata = fopen(argv[1], "r"); //read data.txt file

    if ( fdata == NULL )
    {
        printf("could not read file %s\n", argv[1] );
        exit( 0 );
    }

    fgets( data, 100, fdata );
    while ( ! feof( fdata ) )
    {
        printf("data: %s", data);
        //this is where i get stuck, idk how to utilize this loop to copy the variable and variable names from the data.txt file i was given...thanks for the help

        /* count how many token characters there are in data[] string */
        num_token = Count_Token( data, '=' );

        if ( num_token > MAX )
        {
            printf("   num token is %d, MAX is %d, stopping program.\n", num_token, MAX );
            fclose( fdata );
            exit( 0 );
        }

        for ( i = 0; i < num_token; i++ )
        {
            /* make sure i index does not exceend declaration size of key and value */
            Get_KeyValue_at_Position( data, token, i, key[i], value[i] );
        }

        fgets( data, 100, fdata );
    }

    fclose(fdata);

    return 0;
}

【讨论】:

    【解决方案2】:

    可能有一些更好的函数可以在 string.h 中做更多你想做的事情 您将不得不计算后勤工作并计算“=”字符的数量并决定如何处理。

    #include <string.h>
    
    char *ptr1, *ptr2;
    char tempstring[100];
    char before[100];
    char after[100];
    
    /* you already have data[] filled... where you get stuck */
    
    ptr1 = strchr( data, '=' );   /* find first occurence of = */
    ptr2 = strrchr( data, '=' );  /* find last occurence of = */
    
    if ( *ptr1 == '\0' )
    {
       /* did not find '=' print error message and stop */
    }
    
    if ( *ptr2 == '\0' )
    {
       /* did not find '=' print error message and stop */
    }
    
    /* below is what you are interested in */
    
    strcpy( tempstr, data );
    
    ptr1 = strchr( tempstr, '=' );
    *ptr1 = '\0';    /* turn = into null */
    strcpy( before, tempstr );
    printf("everything before = character is %s\n", tempstr );   /* watch out if = is first character, nothing before it */
    
    
    
    
    
    
    strcpy( tempstr, data );
    
    ptr2 = strchr( tempstr, '=' );
    ptr2++;
    if ( *ptr2 != '\0' )    /* = might have been last character */
    {
       strcpy( after, tempstr );
        printf("everything after = character is %s\n", tempstr );
    }
    

    所以对于第一个 strchr 调用, before[] 将有“recipName” 并且 after[] 将有 "Fork friend=Cup sonName=Spork feature=hair sendName=Spoon"

    你可以做一个 sscanf(之后,“%s”,after2); 假设总会有一个空格字符分隔事物,将“Fork”放入 after2[] 数组中。

    【讨论】:

    • 这个答案质量很差:代码应该放在一个函数中并适当缩进。
    猜你喜欢
    • 2021-05-24
    • 1970-01-01
    • 2016-07-30
    • 2011-01-25
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多