简体   繁体   English

C 编程 - 从文本文件中读取特定行

[英]C Programming - Read specific line from text file

Here is the code :这是代码

int main()
{
    struct vinnaren
    {
        char vinnare[20];
        int artal;
    };
    struct vinnaren v[10];
    int inputrader;
    int antalrader;  //I want antalrader to be equal to the first 
                     //line in test.txt(the first line is "5")
    char file_name[256] = "test.txt";
    char buf[512];
    FILE *f = fopen(file_name, "r");
    if (!f)
    {
        exit(0);
    }
    while (fgets(buf, sizeof buf, f))
    {

        printf("%s", buf);
    }
    fclose(f);
}

This is the code I have.这是我的代码。 I want to make it so that antalrader = line1 in the file test.txt How do I read a specific line from the file?我想让 antalrader = line1 在文件 test.txt 如何从文件中读取特定行?

With this code you can read a file line by line and hence read a specific line from the text file:使用此代码,您可以逐行读取文件,从而从文本文件中读取特定行:

lineNumber = x;

static const char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if ( file != NULL )
{
    char line[256]; /* or other suitable maximum line size */
    while (fgets(line, sizeof line, file) != NULL) /* read a line */
    {
        if (count == lineNumber)
        {
            //use line or in a function return it
            //in case of a return first close the file with "fclose(file);"
        }
        else
        {
            count++;
        }
    }
    fclose(file);
}
else
{
    //file doesn't exist
}

I got a really simple answer but I don't know if it is helping anyone:我得到了一个非常简单的答案,但我不知道它是否对任何人有帮助:

int OpenCommand(int idOfCommand)
{
    fscanf(file_ptr, "%[^idOfCommand]",a[idOfCommand]);
    printf("%d\n", a[idOfCommand]);
    system("pause");

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM