c语言怎么读写txt文件
时间: 2024-06-30 21:00:28 浏览: 97
在C语言中,读写文本文件(TXT文件)通常使用标准库中的`stdio.h`和`fopen`、`fclose`、`fprintf`、`fscanf`等函数。这里提供一个简单的例子,展示了如何打开文件、写入数据和读取数据。
**写入TXT文件(追加模式):**
```c
#include <stdio.h>
void write_to_file(const char *filename, const char *data) {
FILE *file = fopen(filename, "a"); // "a" for append
if (file == NULL) {
perror("Failed to open file");
return;
}
fprintf(file, "%s\n", data); // 输出数据,换行符"\n"可选
fclose(file);
}
// 使用示例
int main() {
char data[] = "Hello, this is a sample text.";
write_to_file("example.txt", data);
return 0;
}
```
**从TXT文件读取数据:**
```c
#include <stdio.h>
char *read_from_file(const char *filename) {
FILE *file = fopen(filename, "r"); // "r" for read
if (file == NULL) {
perror("Failed to open file");
return NULL;
}
char *buffer = malloc(1024); // 假设最多读取1024字节
size_t len;
fgets(buffer, 1024, file); // 读取一整行
len = strlen(buffer);
buffer[len-1] = '\0'; // 去掉换行符
fclose(file);
return buffer;
}
// 使用示例
int main() {
char *text = read_from_file("example.txt");
if (text) {
printf("Read from file: %s\n", text);
free(text); // 释放内存
} else {
printf("Failed to read from file.\n");
}
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)