用c语言写一个查询指定文件的代码
时间: 2024-06-10 16:07:32 浏览: 8
您好!以下是用C语言写一个查询指定文件的代码的示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char filename[50];
char ch;
int line_count = 0, char_count = 0;
printf("请输入文件名: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("无法打开该文件!\n");
exit(0);
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n') {
line_count++;
} else {
char_count++;
}
}
printf("该文件中共有 %d 行,%d 个字符。\n", line_count, char_count);
fclose(fp);
return 0;
}
```
希望对您有所帮助!如果您有其他问题,请继续提出,我会尽可能为您解答。
相关问题
用C语言写一个能查询文件中的指定数据的代码
Sure, here is a simple C program that can search for a specific data in a file:
```
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char search[50], line[200];
printf("Enter data to search: ");
scanf("%s", search);
fp = fopen("filename.txt", "r");
if(fp == NULL)
{
printf("File not found.\n");
return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
if(strstr(line, search) != NULL)
{
printf("%s", line);
}
}
fclose(fp);
return 0;
}
```
Please note that you need to replace "filename.txt" with the actual filename you want to search in, and modify the data type and size of "search" and "line" to fit your needs.
用C语言写一个删除指定目录下所有文件的函数
好的,我可以回答这个问题。以下是一个用C语言编写的删除指定目录下所有文件的函数的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int delete_files(char *path) {
DIR *dir;
struct dirent *entry;
char file_path[256];
dir = opendir(path);
if (dir == NULL) {
printf("Error: Failed to open directory %s\n", path);
return -1;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
sprintf(file_path, "%s/%s", path, entry->d_name);
remove(file_path);
}
closedir(dir);
return 0;
}
```
这个函数接受一个字符串参数,表示要删除文件的目录路径。它使用 opendir() 函数打开目录,然后使用 readdir() 函数遍历目录中的所有文件和子目录。对于每个文件,它使用 sprintf() 函数构造文件的完整路径,然后使用 remove() 函数删除文件。最后,它使用 closedir() 函数关闭目录。
请注意,这个函数只能删除目录中的文件,而不能删除子目录。如果您需要删除整个目录,您需要使用递归函数来删除子目录。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)