这个问题被提出了很多,但特别是关于包含指针的结构,并且从未完全帮助我的情况。我正在尝试做的是strtok()基于“|”的第一个也是唯一一个命令行参数字符。例如,它将类似于:“ls -l | grep ^ d | wc -l。”完成后,我想写一个LOGFILE我标记的项目。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
void main(void)
{
FILE *logfp = fopen("LOGFILE", "w");
char * commands;
char * container[4];
char commandLine[] = ("test|test2|test3|test4\n");
int i = 0;
commands = strtok(commandLine, "|");
while(commands != NULL)
{
container[i] = commands;
printf("Being stored in container: %s\n", container[i]);
i++;
commands = strtok(NULL, "|");
}
printf("This is the size of the container: %d\n", (int)sizeof(container));
fwrite(container,1,sizeof(container),logfp);
fclose(logfp);
}
指针上的sizeof()返回8而不是char的正确数量,这是另一个问题。除此之外,日志文件中充满了我猜测的是指针所指向的内存地址。我想将标记化的字符串写入LOGFILE。我该怎么办?
答案 0 :(得分:3)
使用sizeof(容器)只是给你一个指针的大小,就像你说的那样。不管它指向什么,这将是8。如果要获取char(1)的大小,可以使用sizeof(* container)取消引用指针。但是,这仍然不是你想要的。
你的方法的问题在于,为了一次性fwrite()所有字符串,它们需要按顺序存储在内存中,而它们不是。顺序存储的唯一内容是容器数组中的char *。这些指针指向实际的字符串数据,这些数据都位于完全不同的内存位置。
话虽如此,解决方案很简单:只需要一次fwrite()一个字符串。
while(commands != NULL)
{
container[i] = commands;
printf("Being stored in container: %s\n", container[i]);
//Write one string, using strlen() to calculate the length
fwrite(container[i], 1, strlen(container[i]), logfp);
i++;
commands = strtok(NULL, "|");
}
但请记住,这些字符串将全部混合在一起。该文件看起来像“testtest2test3test4”,除非您在它们之间明确添加空格或换行符。