如何在文件每行末尾继续添加数据
时间: 2024-04-16 21:28:00 浏览: 130
要在文件的每行末尾继续添加数据,您可以使用以下步骤:
1. 打开文件:使用`fopen`函数以追加模式("a")打开要操作的文件。
```c
FILE *file = fopen("filename.txt", "a");
if (file == NULL) {
printf("无法打开文件\n");
return;
}
```
2. 逐行读取文件内容并添加数据:使用`fgets`函数逐行读取文件内容,并使用`strcat`函数将要添加的数据追加到每行末尾。
```c
char line[256];
while (fgets(line, sizeof(line), file)) {
// 去除行尾的换行符
line[strcspn(line, "\n")] = '\0';
// 在每一行的末尾添加数据
strcat(line, "要添加的数据");
// 将修改后的内容写回文件
fprintf(file, "%s\n", line);
}
```
3. 关闭文件:使用`fclose`函数关闭文件。
```c
fclose(file);
```
完整示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
FILE *file = fopen("filename.txt", "a");
if (file == NULL) {
printf("无法打开文件\n");
return 0;
}
char line[256];
while (fgets(line, sizeof(line), file)) {
line[strcspn(line, "\n")] = '\0';
strcat(line, "要添加的数据");
fprintf(file, "%s\n", line);
}
fclose(file);
return 0;
}
```
请注意,这种方法会在文件的末尾添加新数据,而不会修改原始文件的内容。
阅读全文
相关推荐













