c - 从文件的前 N ​​个文件中读取数字

标签 c file-io

我有一个文本文件,每行一个数字。

我想从此文件中读取特定行数,比如说前 20 行,该怎么做?

我有以下代码。

FILE *ft;
ft=fopen(filename,"r");
for(int k=1; k<Nt+1; k=k+1) 
{
    fscanf(ft,"%lf\n",&curve3[k]);
    printf("%lf\n",curve2[k]);
}

编辑:我将代码更改为

FILE *ft;
ft=fopen(filename,"r");
int k=1;

while(!feof(ft))
{
    if(k<=Nt)
    {
        fscanf(ft,"%lf\n",&curve2[k]);
        //printf("%lf\n",curve2[k]);
    } 
    k=k+1;
}

看来还是不行。

最佳答案

使用此代码,您可以逐行读取文件,从而从文本文件中读取特定行。因此,您可以修改代码。

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 - 从文件的前 N ​​个文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30792585/

相关文章:

C 帮助尝试以 10 为底的对数工作

c - 从c代码到时序图的逆向工程

C# 读取 .txt 文件格式化

java - 如何检查文本板中的下一个空行并附加下一个输入

c - 如何更正此代码以检查字谜?

java - 我应该如何订购 if 语句?

c# - 每次写入一行时都写入日志文件 : using (. .. new StreamReader)?

c# - 文件无法访问,因为它正在被另一个程序使用

c - 在 C 中制作一个 makefile

c++ - open() 的参数太多