0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_HEIGHT 5
#define MAX_WIDTH 9
#define MAX_DIRECT 30
typedef struct position_t position_t;
struct position_t {
char *position;
char *ptr;
};
int main(int argc, char *argv[])
{
int i;
FILE *fp;
char a[50], b[50], c[50], d[50];
position_t pos;
pos.position = malloc(sizeof(char) * 20);
for (i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "cat: can't open %s\n", argv[i]);
continue;
}
fgets(a, 50, fp);
fgets(b, 50, fp);
fgets(c, 50, fp);
fgets(d, 50, fp);
fclose(fp);
while (1) {
int j = 0;
pos.position = 0;
pos.ptr = strtok(a, ",.; ");
while (pos.ptr != NULL) {
pos.position[j] = *pos.ptr;
j++;
pos.ptr = strtok(NULL, ",.; ");
}
printf("%c", pos.position[j]);
}
}
free(pos.position);
return 0;
}
我想要做的是从文件中读取第一行(它的内容是:START FOYER ELEVATOR)并通过strtok将它们分隔空间,然后将每个字符串存储在malloc pos中。定位并在以后使用时使用。有人可以修复此代码吗?如何正确使用malloc和strtok?
我建议你阅读[关于铸造'malloc'返回的这个问题](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 –