c语言代码,判断文件中是否有指定字符串,如果没有把该字符串写进该文件
时间: 2024-03-10 09:46:37 浏览: 77
可以使用C语言中的文件操作函数来实现这个功能。具体步骤如下:
1. 打开文件:使用fopen函数打开指定文件,可以选择只读方式或读写方式打开文件。
2. 判断文件中是否有指定字符串:使用fgets函数逐行读取文件内容,使用strstr函数判断每一行中是否包含指定字符串。
3. 如果文件中没有指定字符串,则在文件末尾写入该字符串:使用fseek函数将文件指针移动到文件末尾,使用fputs函数将指定字符串写入文件中。
4. 关闭文件:使用fclose函数关闭文件。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp;
char filename[] = "test.txt";
char str[] = "hello world";
char buffer[1024];
// 打开文件
fp = fopen(filename, "r+");
if (fp == NULL) {
printf("Failed to open file\n");
return 1;
}
// 判断文件中是否有指定字符串
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
if (strstr(buffer, str) != NULL) {
printf("String found in file\n");
fclose(fp);
return 0;
}
}
// 文件中没有指定字符串,写入该字符串
fseek(fp, 0, SEEK_END);
fputs(str, fp);
printf("String written to file\n");
// 关闭文件
fclose(fp);
return 0;
}
```
这个代码会打开名为 test.txt 的文件,然后判断文件中是否包含字符串 "hello world"。如果文件中已经包含该字符串,则输出 "String found in file";如果文件中没有该字符串,则在文件末尾写入该字符串并输出 "String written to file"。最后关闭文件。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)