c - 在目录的每个文件中追加一行

标签 c file io append

我想用 c 编写一个程序,在某个目录中的每个现有文件中 append 一行带有 .txt 后缀的文本。

这可能吗?如何实现?

我使用的是 Windows。

我使用的编译器是gcc

最佳答案

如果您的操作系统是 Windows,请考虑使用函数 _findfirst()_findnext()_findclose() 来扫描目录。要打开文件并向其追加,请使用带有追加模式的 fopen_s()fprintf()。试试这个:

#include <stdio.h>
#include <string.h>
#include <io.h>


int main(void)
{
    struct _finddata_t c_file;
    long hFile;
    char *ptr;
    FILE *file;
    //current directory
    if ((hFile = _findfirst("./*", &c_file)) == -1L) {
        return 1;
    }
    else
    {
        while (_findnext(hFile, &c_file) == 0)
        {
            if (!(c_file.attrib & _A_SUBDIR)) {
                ptr = c_file.name + strlen(c_file.name) - 4;
                if (strstr(ptr, ".txt")) {
                    if (fopen_s(&file, c_file.name, "a")) {
                        fprintf(stderr, "Unable to open file %s in append mode\n", c_file.name);
                        continue;
                    }
                    fprintf(file, "This is an appended text!");
                    fclose(file);
                }
            }
        }
        _findclose(hFile);
    }
    return 0;
}

关于c - 在目录的每个文件中追加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35916490/

相关文章:

c - write(2) 失败怎么办?

c - 返回二维数组或指向一个的指针

php - 从 php 调用 c

c - 写入文件时为"Access violation writing location"

io - 使用 Lua I/O 函数创建新文件

c - 动态数组代码不断崩溃

c - 如何在文本文件中添加多行

android - 如何从 txt 文件中获取某些值?

io - buffio.Scanner 和 text/scanner.Scanner 有什么区别?

java - java中网络字节顺序到主机字节顺序