C语言获取文本文件行数
时间: 2024-05-16 11:01:30 浏览: 123
要使用C语言获取文本文件的行数,可以使用以下代码示例中的其中一种方法:
方法一:
```c
#include<stdio.h>
#include<stdlib.h>
int main() {
int line_count = 0;
char ch;
FILE *file;
file = fopen("record.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
exit(1);
}
while ((ch = fgetc(file)) != EOF) {
if (ch == '\n') {
line_count++;
}
}
printf("该文件中的行数为:%d\n", line_count);
fclose(file);
return 0;
}
```
在这个方法中,我们打开待统计行数的文件并逐个读取字符。每当我们遇到一个换行符('\n')时,行数就增加1。最后,我们输出行数。
方法二:
```c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
int line_count = 0;
char file_name<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [统计txt文件中的行数——C语言设计](https://blog.csdn.net/m0_64316589/article/details/124375207)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [【C语言编程】统计一个文本文件的行数](https://blog.csdn.net/yyyjyou/article/details/21938815)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [Java与C语言混合开发技术](https://download.csdn.net/download/milk416666/88249349)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文