如何通过C读取txt文件指定的一行字符串
时间: 2024-02-06 22:03:19 浏览: 32
可以使用fgets函数来读取指定行号的字符串。首先使用fopen函数打开txt文件,然后使用fseek函数将文件指针移动到指定行的开头位置,最后使用fgets函数读取该行的字符串。示例代码如下:
```c
#include <stdio.h>
int main() {
FILE *file;
char filename[100] = "/path/to/file.txt";
int line_num = 5; // 要读取的行号,这里假设是第5行
char line[100];
file = fopen(filename, "r");
if (file == NULL) {
printf("无法打开文件 %s\n", filename);
return 1;
}
// 移动文件指针到指定行的开头位置
for (int i = 1; i < line_num; i++) {
if (fgets(line, 100, file) == NULL) {
printf("文件 %s 不足 %d 行\n", filename, line_num);
return 1;
}
}
// 读取指定行的字符串
if (fgets(line, 100, file) != NULL) {
printf("第 %d 行的字符串是:%s", line_num, line);
} else {
printf("文件 %s 不足 %d 行\n", filename, line_num);
}
fclose(file);
return 0;
}
```