C编程 - 从文本文件读取特定的行 [英] C Programming - Read specific line from text file

查看:143
本文介绍了C编程 - 从文本文件读取特定的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码

  int main()
{
struct vinnaren
{
char vinnare [20];
int artal;
};
struct vinnaren v [10];
int inputrader;
int antalrader; //我想让antalrader等于test.txt中的第一行
//(第一行是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);



$ b $ p $这是我的代码。我希望在文件test.txt中添加
antalrader = line1
如何从文件中读取特定的行

解决方案

使用此代码,您可以逐行读取文件,并从文本文件中读取特定行:

  lineNumber = x; 

static const char filename [] =file.txt;
FILE * file = fopen(filename,r);
int count = 0;
if(file!= NULL)
{
char line [256]; / *或其他合适的最大行大小* /
while(fgets(line,sizeof line,file)!= NULL)/ *读一行* /
{
if(count == lineNumber)
{
//使用行或函数返回
//在返回的情况下,首先用fclose(file)关闭文件;
}
else
{
count ++;
}
}
fclose(file);
}
else
{
//文件不存在
}


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?

解决方案

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
}

这篇关于C编程 - 从文本文件读取特定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆