我如何使用sprintf的输出作为fopen的文件名?

时间:2012-05-08 23:46:01

标签: c file-io

我正在开发一个日志解析程序,它通过组合环境变量和预设字符串来检索要打开的文件,以便提供文件的完整路径,但是我无法让fopen从中取出输出sprintf,我用来组合环境变量和预设字符串,所以我想知道是否有人可以提供建议,我应该怎么做才能让它正常工作?谢谢! (我刚刚开始在过去的几个星期里自学C语言,所以无论他们对我有多么明显,我都会接受任何提示)

#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 **’

1 个答案:

答案 0 :(得分: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的结果超出预期,则可以避免令人不快的意外。