0

我正在开发一个日志解析程序,该程序通过组合环境变量和预设字符串来检索要打开的文件,以便提供文件的完整路径,但是我无法让 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 **’
4

1 回答 1

3
char *filename[];

char声明一个未知大小的指针数组。您需要一个足够已知长度的charto to数组。sprintf宣布

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如果结果比预期的要长,以避免不愉快的意外。

于 2012-05-08T23:49:02.617 回答