用c语言将一个文件中的数据有选择性的输入另一个文件
时间: 2024-03-14 13:46:14 浏览: 22
要实现有选择性地将一个文件中的数据输入到另一个文件,可以在读取文件的过程中添加一些条件判断,决定是否将数据写入到要写入的文件中。下面是一个示例代码,可以按照指定的条件选择性地将一个文件中的数据输入到另一个文件中:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp_read, *fp_write;
char buffer[1024];
char keyword[] = "hello"; // 指定关键字
// 打开要读取的文件
fp_read = fopen("input.txt", "r");
if (fp_read == NULL) {
printf("Error: cannot open input file.\n");
return -1;
}
// 打开要写入的文件
fp_write = fopen("output.txt", "w");
if (fp_write == NULL) {
printf("Error: cannot open output file.\n");
fclose(fp_read);
return -1;
}
// 从要读取的文件中读取数据,并根据指定条件选择性地写入到要写入的文件中
while (fgets(buffer, sizeof(buffer), fp_read)) {
if (strstr(buffer, keyword) != NULL) { // 如果读取到的数据包含指定关键字
fwrite(buffer, sizeof(char), strlen(buffer), fp_write); // 写入到要写入的文件中
}
}
// 关闭文件
fclose(fp_read);
fclose(fp_write);
return 0;
}
```
在这个示例代码中,我们首先指定了一个关键字"hello"。然后打开要读取的文件和要写入的文件。在读取文件的过程中,我们使用strstr函数判断读取到的数据中是否包含关键字。如果包含,则使用fwrite函数将数据写入到要写入的文件中。最后关闭打开的文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)