c - 如何将文本文件的一部分复制到C中的字符串中?

标签 c string file io

我有一个文本文件:

recipName=Fork friend=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;
}

最佳答案

可能有一些更好的函数可以在 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[] 将有“Forkfriend=CupsonName=Sporkfeature=hairsendName=Spoon”

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

关于c - 如何将文本文件的一部分复制到C中的字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34971109/

相关文章:

c - 使用链表分隔偶数和奇数的函数

c++ - unsigned short 和 signed short 比较奇怪的行为

c - 你什么时候会使用字符串而不是字符?

java - 异常消息可以包含Java中的正则表达式字符吗?

c - 复合语句( block )是否被 ANSI C 中的括号表达式包围?

c++ - 在 C/C++ 中防止缓冲区溢出

c - 为什么 fgetc 或 fgets 忽略

javascript - 如何使用 jquery javascript 对表格中的文件夹和文件进行排序

带有单引号查找的 Java 正则表达式错误?

java - 是否可以将文件保存到任何集合(例如 HashMap 或哈希表)中?