编写c语言代码读取文件行数
时间: 2023-12-25 14:48:02 浏览: 59
当然可以,以下是读取文件行数的C语言代码示例:
```c
#include <stdio.h>
int main() {
FILE *fp;
int lines = 0;
char ch;
fp = fopen("file.txt", "r"); //打开文件,file.txt为文件名
if (fp) { //如果文件打开成功
while ((ch = fgetc(fp)) != EOF) { //逐个字符读取文件内容
if (ch == '\n') { //如果读到换行符,则行数加1
lines++;
}
}
fclose(fp); //关闭文件
}
printf("The file has %d lines.\n", lines); //输出文件行数
return 0;
}
```
请注意,在代码中,我们假设文件名为“file.txt”,可以根据实际需要自行修改。
相关问题
c语言编写程序读取网页文件(例如:a.htm),找出标题内容以及在文件中行数写入文件result.txt中
好的,这里提供一个使用C语言实现的程序,同样需要使用第三方库libxml2来解析HTML文件。需要注意的是,这个程序只能在Linux系统下运行。
首先,我们需要安装libxml2库,你可以使用以下命令安装:
```
sudo apt-get install libxml2-dev
```
接下来,我们可以编写程序:
```c
#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
int main() {
// 读取HTML文件
FILE *fp;
char *filename = "a.htm";
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file: %s\n", filename);
return 1;
}
fseek(fp, 0L, SEEK_END);
int filesize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char *html = malloc(filesize + 1);
fread(html, sizeof(char), filesize, fp);
fclose(fp);
// 解析HTML文件
xmlDocPtr doc;
xmlNodePtr node;
doc = xmlReadMemory(html, filesize, "noname.xml", NULL, 0);
if (doc == NULL) {
printf("Failed to parse document\n");
return 1;
}
node = xmlDocGetRootElement(doc);
// 找到标题内容
xmlNodePtr title_node;
title_node = xmlGetFirstElementChild(node);
while (title_node != NULL && strcmp((char *)title_node->name, "title") != 0) {
title_node = xmlGetNextElementSibling(title_node);
}
if (title_node == NULL) {
printf("Failed to find title\n");
return 1;
}
char *title = (char *)xmlNodeListGetString(doc, title_node->xmlChildrenNode, 1);
// 找到行数
int lines = 0;
char *pch = strchr(html, '\n');
while (pch != NULL) {
lines++;
pch = strchr(pch+1, '\n');
}
// 写入结果文件
FILE *fp_out;
char *filename_out = "result.txt";
fp_out = fopen(filename_out, "w");
if (fp_out == NULL) {
printf("Failed to open file: %s\n", filename_out);
return 1;
}
fprintf(fp_out, "Title: %s\nLines: %d", title, lines);
fclose(fp_out);
// 释放内存
free(html);
xmlFree(title);
xmlFreeDoc(doc);
return 0;
}
```
这个程序会读取名为a.htm的文件,解析其中的HTML代码,并找到标题内容和行数,然后将结果写入名为result.txt的文件中。你只需要将a.htm文件放在程序所在的目录下,然后编译运行程序即可。
用C语言编写:通过输入磁盘文件my.txt中内容,然后再统计文件中的字符个数和行数
可以按如下方式编写C语言代码:
```c
#include <stdio.h>
int main() {
FILE *fp;
char ch;
int char_count = 0, line_count = 0;
// 打开文件
fp = fopen("my.txt", "r");
// 逐个读取字符,统计字符个数和行数
while ((ch = fgetc(fp)) != EOF) {
char_count++;
if (ch == '\n') {
line_count++;
}
}
// 关闭文件
fclose(fp);
// 输出结果
printf("字符个数:%d\n", char_count);
printf("行数:%d\n", line_count);
return 0;
}
```
这个程序首先打开名为“my.txt”的文件,然后逐个读取文件中的字符,同时统计字符个数和行数。为了实现逐个读取,我们使用了`fgetc()`函数。当读取到文件末尾时,`fgetc()`函数会返回特殊的EOF值,我们可以用`EOF`宏来表示它。
在每次读取到换行符`\n`时,我们将行数加1。最后输出统计结果即可。注意,这里的行数指的是文件中的行数,不包括最后一行末尾没有换行符的情况。