我需要一个小脚本,将“\ n exit”追加到〜/ ae23054 /我的代码中所有文件的末尾:
#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;
}
但我在编译时遇到此错误:gcc test.c
esempio_giuseppe.c: In function ‘main’:
esempio_giuseppe.c:16: error: invalid initializer
esempio_giuseppe.c:18: error: ‘a’ undeclared (first use in this function)
esempio_giuseppe.c:18: error: (Each undeclared identifier is reported only once
esempio_giuseppe.c:18: error: for each function it appears in.)
esempio_giuseppe.c:18: error: expected expression before ‘)’ token
感谢您的帮助
我有这个错误:
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
答案 0 :(得分:3)
您需要将fopen
的第二个参数设为字符串,因为它需要const char*
FILE *fd=fopen(nome_file, "a+");
^ ^
^ ^
而不是
FILE *fd=fopen(nome_file, a+);
另请参阅@AlterMann关于文件名缓冲区的答案。
答案 1 :(得分:0)
问题出在char nome_file[256]=ep->d_name;
您需要使用strcpy()
复制字符串,例如strcpy(nome_file,ep->d_name);
,并将FILE *fd=fopen(nome_file, a+);
更改为FILE *fd=fopen(nome_file, "a+");