C语言获取文件中的行数
时间: 2023-09-13 20:12:40 浏览: 668
可以使用以下代码来获取文件中的行数:
```c
#include <stdio.h>
int main() {
char filename[100];
int count = 0;
char c;
printf("Enter filename: ");
scanf("%s", filename);
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("File not found!\n");
return 0;
}
while ((c = fgetc(fp)) != EOF) {
if (c == '\n') {
count++;
}
}
fclose(fp);
printf("Number of lines in %s is %d\n", filename, count);
return 0;
}
```
该程序通过打开文件,逐个读取文件中的字符,当遇到换行符时,行数加1,最后输出行数。注意在程序结束时要关闭文件。
相关问题
C语言获取文本文件行数
要使用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 ]
C语言获得txt文件行数
可以使用C语言中的文件操作函数来获得txt文件的行数。具体步骤如下:
1. 打开文件,使用fopen函数打开txt文件,获取文件指针。
2. 逐行读取文件内容,使用fgets函数逐行读取文件内容,每读取一行,计数器加1。
3. 关闭文件,使用fclose函数关闭文件。
下面是示例代码:
```c
#include <stdio.h>
int main() {
FILE *fp;
int count = 0;
char buffer[512];
fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
count++;
}
fclose(fp);
printf("The file has %d lines\n", count);
return 0;
}
```
其中,"file.txt"是要读取的txt文件名。