我正在尝试在我的代码中执行以下操作,这是C语言中textsort的实现。
-data []包含指向从文件中读取的句子的指针。
复制“数据”数组的第j个内容,并将其存储在行缓冲区char *中。 (此数组是一个指针数组,实例化为const char ** data,并以以下方式进行malloc-ed:data = malloc(sizeof(char *)* numlines))
然后我尝试使用空格作为分隔符将句子分成单词。
-最后,我正在尝试将strtok返回的指针存储在初始化为char * tokenarray和malloc-ed为tokenarray = malloc(sizeof(char *)* numlines)的指针数组中。这是代码:
`
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MAXCHAR 150
#define COPYMAX 150
char inpstr[MAXCHAR]; //char array for the input string storage
char copyd[MAXCHAR]; // copy needed for some fxn
char *temp_bffr;
size_t buffsize;
int status;
char filename;
int numlines;
numlines = 5;
int i;
char *storedline;
FILE *fileo; //fopen pointer
const char **data;
int separate_words(char ** txtarray){
printf("separating\n");
char *token; //for strtok
char *tokenarray;
int j;
char *linebuffer = (char *) malloc(MAXCHAR); //malloc since we want to modify this copy?
tokenarray = malloc(sizeof(char *)*numlines);
for(j = 0; j<= numlines; j++){
//printf("Element[%d] = %d\n", j, data[j]);
strcpy(linebuffer, data[j]);
token = strtok(linebuffer, " ");
tokenarray[j] = token;
}
return 0;
}
int my_compare(const void *elem1, const void *elem2){
printf("comparing is hard");
//qsort????
return 0;
}
int main(){
fileo = fopen("short_alma.txt","r");
data = (char **)malloc(numlines * sizeof(char *));
//check stats from file
struct stat buffer;
if(fstat(status, &buffer) != 0){
printf("error: fstat()\n");
exit(1);
}
// temporary buffer
temp_bffr = malloc(sizeof(char)* (MAXCHAR +1));
i = 0;
//usefgets to start reading:
while(fgets(temp_bffr, MAXCHAR, fileo)){
//printf("temp_bffr is : \n");
//puts(temp_bffr);
//check sizeif line < MAX, save size and do realloc()
if(strlen(temp_bffr) < MAXCHAR){
buffsize = strlen(temp_bffr);
//malloc memory using buffer size before the string copy??? is this it???
data[i] = malloc(sizeof(char)*numlines);
strcpy(data[i], temp_bffr);
i++;
}
else{
printf("line has too many chars!");
}
}
separate_words(data); //separate the strings in our array
//return data;
return 0;
}
`