我有一个文本文件,每行一个数字。
我想从此文件中读取特定行数,比如说前 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/