C 在二维数组中从文件中读取字
我正在尝试使用C语言中的“动态”数组。我希望这段代码能够被读取C 在二维数组中从文件中读取字,c,file-io,C,File Io,我正在尝试使用C语言中的“动态”数组。我希望这段代码能够被读取 printer,kekroflmeow,augustus,rofl,mao,kek,burger,lol,zomg,apo,abe,ago,lorem,ipsum,solar,sit,whan,kong,ping,roflstomp,dennis,hotdog,ketchup,viva,north 并将其存储在2D数组中(动态地,我希望能够添加和删除单词)。单词长度不能超过20个字符。我让它大部分工作,我有两个问题,char**s
printer,kekroflmeow,augustus,rofl,mao,kek,burger,lol,zomg,apo,abe,ago,lorem,ipsum,solar,sit,whan,kong,ping,roflstomp,dennis,hotdog,ketchup,viva,north
并将其存储在2D数组中(动态地,我希望能够添加和删除单词)。单词长度不能超过20个字符。我让它大部分工作,我有两个问题,char**str来自主文件,变量是char*mWords[20],但是这似乎意味着它可以包含20个未定义长度的单词,这与我想要的相反
您可能还需要getWordsFroMFile(char**str)函数
// get words from file; delimiter , stores them in str[word][character]
int getWordsFromFile (char **str) {
FILE *tFile;
int file_size;
char *file_ptr;
// load the file and check if it exists
tFile = fopen(FILENAME, "r");
if (tFile == NULL) {
printf ("Cannot open file '%s'", FILENAME);
exit (1);
}
// get size of file in bytes (1 byte = 1 char)
fseek (tFile , 0 , SEEK_END);
file_size = ftell (tFile);
// back to start of tFile
rewind (tFile);
// allocate memory
file_ptr = (char*) malloc (file_size);
if (file_ptr == NULL) {
printf ("Could not read file '%s'", FILENAME);
exit (2);
}
// file -> buffer
int size = fread (file_ptr, 1, file_size, tFile);
file_ptr[size] = '\0';
fclose(tFile);
char * pch;
pch = strtok (file_ptr, ",");
int tWords = 0;
while (pch != NULL) {
if (sizeof(pch) < MAX_WORD_LEN && pch != "") {
// if word only contains valid characters A-Z and/or a-z
if (isValidWord(pch)) {
// good, remove trim word and place it in str[tWords]
str[tWords++] = trimWord(pch);
} else {
printf ("Invalid word in '%s': '%s' contains illegal characters.\n", FILENAME, pch);
}
}
pch = strtok (NULL, ",");
}
return tWords;
}
更新了fread()以添加终止\0
提前感谢,
Emz第一个简单问题:除非你想的是完全其他的东西,
fread
做你认为它会做的事情:读取n字节。但它不知道您要将该数据视为C字符串,因此您必须在字符串中添加一个终止零。非常有用,谢谢。我猜这是一个问题,但我并没有试图解决它,而是试图找出另一个问题。谢谢sizeof(pch)
-->strlen(pch)
,pch!=“
-->*pch!=”\0'
文件大小=ftell(tFile)代码>可能不是正确的文件大小。您仍然需要分配额外的零字节。此外,在使用fread时,应使用文件打开模式“rb”(用于“二进制”)以避免回车/换行转换。
char *mWords[MAX_WORD_LEN];
int mWordsCount = getWordsFromFile (mWords);