Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在目录的每个文件中追加一行_C_File_Io_Append - Fatal编程技术网

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

C 在目录的每个文件中追加一行,c,file,io,append,C,File,Io,Append,我想用c语言编写一个程序,在某个目录中的每个现有文件中添加一行文本,后缀为.txt 这可能吗?如何实现 我正在使用windows 我使用的编译器是gcc,当然这是可能的 如果您在POSIX上,您可以使用和朋友扫描目录层次结构。您可以编写一个简单的函数来检查字符串是否以“.txt”结尾,并使用该函数筛选出要修改的文件。然后只需使用fopen()、fseek()和fprintf()进行追加 对于其他平台,目录扫描部分必须更改。 < P>如果您的操作系统是Windows,请考虑使用函数 yFixFix

我想用c语言编写一个程序,在某个目录中的每个现有文件中添加一行文本,后缀为.txt

这可能吗?如何实现

我正在使用windows


我使用的编译器是gcc,当然这是可能的

如果您在POSIX上,您可以使用和朋友扫描目录层次结构。您可以编写一个简单的函数来检查字符串是否以
“.txt”
结尾,并使用该函数筛选出要修改的文件。然后只需使用
fopen()
fseek()
fprintf()
进行追加


对于其他平台,目录扫描部分必须更改。

< P>如果您的操作系统是Windows,请考虑使用函数<代码> yFixFixStand(<代码> > <代码> > FunnExt())/>代码>和<代码>×FixCuffe()/Cyto>扫描目录。打开文件并附加到它,使用<代码> fOpenSH()/<代码>附加模式,以及<代码> fPINTFF()。。请尝试以下操作:

#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;
}
#包括
#包括
#包括
内部主(空)
{
结构finddata t c_文件;
长纤维;
char*ptr;
文件*文件;
//当前目录
if((hFile=_findfirst(“./*”,&c_文件))==-1L){
返回1;
}
其他的
{
while(_findnext(hFile,&c_文件)==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,“无法在追加模式下打开文件%s\n”,c_file.name);
继续;
}
fprintf(文件,“这是一个附加文本!”);
fclose(文件);
}
}
}
_findclose(hFile);
}
返回0;
}

您正在使用什么操作系统?是的,这是可能的。您必须在目录中列出*.txt文件(这取决于平台),然后针对每个文件以追加模式打开文件,写入行,关闭文件。