C语言中的一个简单程序,用于向目录中的所有文件追加字符串

C语言中的一个简单程序,用于向目录中的所有文件追加字符串,c,linux,unix,command-line,C,Linux,Unix,Command Line,我需要一个小脚本,在~/ae23054/中的所有文件末尾添加“\n exit”。我的代码是: #include <stdio.h> #include <sys/types.h> #include <dirent.h> int main (void) { DIR *dp; struct dirent *ep; const char *path_dir ="~ae23054/Giuseppe";//I

我需要一个小脚本,在~/ae23054/中的所有文件末尾添加“\n exit”。我的代码是:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

     int main (void)
     {
       DIR *dp;
       struct dirent *ep;
       const char *path_dir ="~ae23054/Giuseppe";//Inserire la directory qui

       dp = opendir (path_dir);
       if (dp != NULL)
         {
           while (ep = readdir (dp)){
             printf(ep->d_name);
             char nome_file[256]=ep->d_name;

             FILE *fd=fopen(nome_file, a+);
             fprint(fd,"\nEXIT");
             fclose(fd);
           }
           (void) closedir (dp);
         }
       else
         perror ("Non posso aprire la directory");

       return -1;
}
谢谢你的帮助


我有以下错误:

char nome_file[256];

strcpy(nome_file, ep->d_name);


ae23054@el088soh:/home/risorse/ae23054/Giuseppe> gcc esempio_giuseppe.c
esempio_giuseppe.c: In function ‘main’:
esempio_giuseppe.c:18: warning: incompatible implicit declaration of built-in function   ‘strcpy’
esempio_giuseppe.c:20: error: ‘a’ undeclared (first use in this function)
esempio_giuseppe.c:20: error: (Each undeclared identifier is reported only once
esempio_giuseppe.c:20: error: for each function it appears in.)
esempio_giuseppe.c:20: error: expected expression before ‘)’ token

您需要将
fopen
的第二个参数设置为字符串,因为它需要
const char*

FILE *fd=fopen(nome_file, "a+");
                          ^  ^
                          ^  ^
而不是

FILE *fd=fopen(nome_file, a+);

另请参见@AlterMann关于文件名缓冲区的回答。

问题在于
字符名文件[256]=ep->d\U名称

您需要使用
strcpy()
来复制字符串,例如,
strcpy(nome\u文件,ep->d\u名称)和更改
文件*fd=fopen(nome_文件,a+
文件*fd=fopen(nome_文件,“a+”)

编写shell脚本会更快。请注意,tilde扩展是shell的一项功能,
opendir()
可能会失败,除非您替换实际的绝对路径。
FILE *fd=fopen(nome_file, a+);