【发布时间】:2016-06-25 07:08:27
【问题描述】:
我想用 c 编写一个程序,在某个目录中的每个现有文件中附加一行文本,并带有 .txt 后缀。
这可能吗?如何实现?
我正在使用 Windows。
我使用的编译器是gcc
【问题讨论】:
-
你使用的是什么操作系统?
-
是的,有可能。您必须列出目录中的 *.txt 文件(这取决于平台),然后为每个文件以附加模式打开文件,写入行,关闭文件。
我想用 c 编写一个程序,在某个目录中的每个现有文件中附加一行文本,并带有 .txt 后缀。
这可能吗?如何实现?
我正在使用 Windows。
我使用的编译器是gcc
【问题讨论】:
如果您的操作系统是 Windows,请考虑使用函数_findfirst()、_findnext() 和 _findclose() 扫描目录。要打开文件并附加到它,请使用 fopen_s() 和 @987654325 附加模式@.试试这个:
#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;
}
【讨论】:
当然可以。
如果您使用的是 POSIX,则可以使用opendir() 和朋友来扫描目录层次结构。您可以编写一个简单的函数来检查字符串是否以".txt" 结尾,并使用它来过滤掉要修改的文件。然后只需使用fopen()、fseek() 和fprintf() 进行追加。
对于其他平台,必须更改目录扫描部分。
【讨论】: