读取文件任意行有两种方法:使用 fseek() 和 fgets() 函数,将文件指针移动到指定行并读取;逐行读取,从文件开头读取直到找到指定行。

如何读取文件任意一行
读取文件任意行的方法有两种:
方法一:使用 fseek() 和 fgets() 函数
<code class="c">int row = 5; // 要读取的行号
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("fopen()");
return -1;
}
// 将文件指针移动到指定行
if (fseek(fp, (row - 1) * sizeof(char), SEEK_SET) != 0) {
perror("fseek()");
fclose(fp);
return -1;
}
// 从文件指针处读取一行
char line[1024];
fgets(line, sizeof(line), fp);
printf("第 %d 行:%s", row, line);
fclose(fp);</code>方法二:使用逐行读取
立即学习“C语言免费学习笔记(深入)”;
从文件开头逐行读取,直到找到指定行。
<code class="c">int row = 5; // 要读取的行号
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("fopen()");
return -1;
}
char line[1024];
int current_row = 1;
while (fgets(line, sizeof(line), fp)) {
if (current_row == row) {
printf("第 %d 行:%s", row, line);
break;
}
current_row++;
}
fclose(fp);</code>以上就是c语言如何读取文件任意一行的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号