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)。 –