簡體   English   中英

用C解析文本文件的內容(刪除零件,存儲其他零件)

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

我有一個基本的.txt文件,該文件可能完全包含這種格式的未知數量的數據,我需要在'='標識符后提取第二部分。 例如:

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

我需要提取“你好”,“如何”,“是”和“你?” 分別將它們存儲到一個數組中(刪除/忽略變量名),並能夠分別調用每個單詞。 我正在用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就足夠了。
  • 無需將文件名copycopy緩沖區。
  • 可能也沒有必要以更新模式"%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")] = '\0';  /* 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;
}

注意一個襯里剝離尾隨\\n在的端左copy通過fgets() copy[strcspn(copy, "\\n")] = '\\0'; 即使fgets()在緩沖區末尾或文件末尾之前沒有看到\\n ,它也可以工作。 strcspn counts返回copy中不在第二個參數中的字符數,因此它返回不帶\\n的行的長度。

這些單詞被收集到一個指向字符串的指針的數組words中。 每個字都由strdup函數復制到malloc分配的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM