C解析文本文件的内容(删除部分,存储其他部分)

Parsing contents of a textfile in C(Deleting parts, storing others)

我有一个基本的 .txt 文件,其中可能包含完全采用这种格式的未知数量的数据,我需要提取“=”标识符后的第二部分。例如:

variable1=Hello
variable2=How
variable3=Are
variable4=You?

我需要分别提取"Hello" "How" "Are"和"You?"并将它们存储到一个数组中(removing/ignoring变量名)并且能够单独调用每个单词。我在 C 中这样做,这就是我目前拥有的。

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

int main()
{
    char*result;
    char copy[256];
    FILE * filePtr;
    filePtr = fopen("testfile.txt", "r+");

    strcpy(copy, "testfile.txt");
    while(fgets(copy, 256, filePtr)!= NULL)
    {
      result = strchr(copy, '=');
      result = strtok(NULL, "=");
      printf("%s",result);
      if(result != 0)
      {
        *result = 0;
      }
    result = strtok(copy, "=");
    }
return 0;
}

我当前的输出是

(null)How
Are
You?
  • 不需要strtok,使用strchr即可。
  • 无需将文件名复制到 copy 缓冲区。
  • 可能也不需要以更新模式打开文件 "%r+"

这是更正后的版本:

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

int main(void) {
    char *words[20];
    int n = 0;
    char *result;
    char copy[256];
    FILE *filePtr;
    filePtr = fopen("testfile.txt", "r");

    while (fgets(copy, 256, filePtr) != NULL) {
        copy[strcspn(copy, "\n")] = '[=10=]';  /* strip the \n if present */
        result = strchr(copy, '=');
        if (result != NULL) {
            words[n++] = strdup(result + 1);
            printf("%s ", result + 1);
        }
    }
    printf("\n");
    fclose(filePtr);
    return 0;
}

注意用 fgets() 去除 copy 末尾留下的尾随 \n 的一行:copy[strcspn(copy, "\n")] = '[=19=]';。即使 fgets() 在缓冲区末尾或文件末尾之前没有看到 \n,它也能工作。 strcspn 计算 returns copy 中不在第二个参数中的字符数,因此它 returns 没有 \n 的行的长度。

单词被收集到一个字符串指针数组 words 中。 strdup 函数将每个单词复制到由 malloc 分配的内存中。 strdup 不是标准 C 的一部分,而是 Posix 的一部分并且可能存在于您的环境中,可能写为 _strdup.

另请注意,您还应测试打开文件失败、在 strdup 中分配内存失败以及处理超过 20 个字符串...

如果有一组固定的单词,而你只想去掉开头的部分,你可以使用更简单的硬编码方法:

int main(void) {
    char word1[20], word2[20], word3[20], word4[20];
    FILE *filePtr;
    filePtr = fopen("testfile.txt", "r");

    if (fscanf(filePtr,
               "%*[^=]=%19[^\n]%*[^=]=%19[^\n]%*[^=]=%19[^\n]%*[^=]=%19[^\n]",
               word1, word2, word3, word4) == 4) {
        printf("%s %s %s %s\n", word1, word2, word3, word4);
        // perform whatever task with the arrays
    } else {
        printf("parse failed\n");
    }
    fclose(filePtr);
    return 0;
}