2012-05-08 116 views
0

我正在处理一个日志解析程序,它通过组合一个环境变量和一个预设字符串来检索要打开的文件,以便提供文件的完整路径,但是我无法从frint中取出sprintf的输出我正在使用它来结合环境变量和预设字符串,所以我想知道是否有人可以提供建议,我应该怎么做才能正常工作?谢谢! (我刚刚开始自学下在过去的几个星期,所以即时通讯开放给任何提示,无论他们应该怎么明显,我)如何使用sprintf的输出作为fopen的文件名?

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define _GNU_SOURCE 
void main(int argc, char *argv[], char *envp[]) 
{ 
    FILE *fd; // File pointer 
    char *name; 
    char *filename[]; 
    name = getenv("MCEXEC_PLAYERNAME"); 
    sprintf(filename,"/home/minecraft/freedonia/playerdata/deathlog-%s.txt",name); 
    char buff[1024]; 
    if ((fd = fopen(filename, "r")) != NULL) // open file 
    { 
    fseek(fd, 0, SEEK_SET); // make sure start from 0 

    while(!feof(fd)) 
    { 
     memset(buff, 0x00, 1024); // clean buffer 
     fscanf(fd, "%[^\n]\n", buff); // read file *prefer using fscanf 
    } 
    printf("Last Line :: %s\n", buff); 
    } 
    else 
    printf("fail"); 
} 

这里是错误,而使用gcc

编译我得到
lastline.c: In function ‘main’: 
lastline.c:9: error: array size missing in ‘filename’ 
lastline.c:11: warning: passing argument 1 of ‘sprintf’ from incompatible pointer type 
/usr/include/stdio.h:341: note: expected ‘char * __restrict__’ but argument is of type ‘char **’ 
lastline.c:13: warning: passing argument 1 of ‘fopen’ from incompatible pointer type 
/usr/include/stdio.h:249: note: expected ‘const char * __restrict__’ but argument is of type ‘char **’ 

回答

3
char *filename[]; 

声明了一个指向未知大小的char的指针数组。你需要一个charsprintf的数组,它具有足够的已知长度。声明

char filename[1000]; // assuming 1000 is large enough 

char *filename; 

为指针,以charmalloc足够的内存,你已经得到了名后,

filename = malloc(sizeof "/home/minecraft/freedonia/playerdata/deathlog-.txt" - 1 + strlen(name) + 1); 
if (!filename) exit(EXIT_FAILURE); 

,以避免不愉快的意外,如果name证明比预期更长。

+0

尽管strlen()通常是一个内置于函数中的编译器,它将会被优化出来,但许多人更喜欢sizeof() - 1作为strlen()的字符串常量。 – johannes

+0

好点,因为我们也想为0终结符的空间,所以'sizeof'甚至摆脱了'+ 1'。 –

+0

关于“摆脱-1”:sizeof() - 1 + strlen()+ 1使意图清晰。只使用sizeof()+ strlen(),必须仔细观察才能看到使用了strlen和sizeof,并为\ 0分配了足够的空间。 – johannes

相关问题