gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:02 24 4
gpt4 key购买 nike

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

最佳答案

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

关于c - 我如何使用 sprintf 的输出作为 fopen 的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10508059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com