簡體   English   中英

如何從文本文件中提取特定編號的行? (C)

[英]How do I extract a specific numbered line from a text file? (C)

我正在嘗試編寫一個函數,該函數根據給定的數字從文本文件中打印特定行。 例如,假設文件包含以下內容:

1 hello1 one
2 hello2 two
3 hello3 three

如果給定的數字為“ 3”,則函數將輸出“ hello3 three”。 如果給定的數字為“ 1”,則函數輸出將為“ hello1 one”。

我對C非常陌生,但到目前為止,這是我的邏輯。

我想首先是第一件事,我需要在文件中找到字符“數字”。 那呢 我如何寫出不包含數字的行? 我什至找不到“數字”? 我敢肯定這很簡單,但是我不知道該怎么做。 這是我到目前為止的內容:

void readNumberedLine(char *number)
{
    int size = 1024;
    char *buffer = malloc(size);
    char *line;
    FILE *fp;
    fp = fopen("xxxxx.txt", "r");
    while(fp != NULL && fgets(buffer, sizeof(buffer), fp) != NULL)
    {
      if(line = strstr(buffer, number))
      //here is where I am confused as to what to do.           
    }
    if (fp != NULL)
    {
            fclose(fp);
    }
}

任何幫助將不勝感激。

從您所說的內容開始,您正在尋找在行首標記有數字的行。 在這種情況下,您需要可以讀取帶有標簽前綴的行的內容

bool readTaggedLine(char* filename, char* tag, char* result)
{
    FILE *f;
    f = fopen(filename, "r");
    if(f == NULL) return false;
    while(fgets(result, 1024, f))
    {
        if(strncmp(tag, result, strlen(tag))==0)
        {
            strcpy(result, result+strlen(tag)+1);
            return true;
        }
    }
    return false;
}

然后像

char result[3000];
if(readTaggedLine("blah.txt", "3", result))
{
    printf("%s\r\n", result);
}
else
{
    printf("Could not find the desired line\r\n");
}

我會嘗試以下。

方法1:

Read and throw away (n - 1) lines 
// Consider using readline(), see reference below
line = readline() // one more time
return line

方法二:

Read block by block and count carriage-return characters (e.g. '\n'). 
Keep reading and throwing away for the first (n - 1) '\n's
Read characters till next '\n' and accumulate them into line
return line

readline(): 在C中一次讀取一行

PS following是一個shell解決方案,可以用於對C程序進行單元測試。

// Display 42nd line of file foo
$ head --lines 42 foo | tail -1
// (head displays lines 1-42, and tail displays the last of them)

您可以使用一個附加值來幫助您記錄已讀取的行數。然后在while循環中將值與輸入值進行比較,如果它們相等,則輸出buffer

暫無
暫無

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

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