gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:04:08 25 4
gpt4 key购买 nike

我想用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com