我有一个文件,其中包含用换行符分隔的不同单词。我如何读取每个单词并将其存储在字符串数组中? 1 个字,数组的 1 行。 我发布了这段代码,但我很确定它不起作用,因为我不明白我应该使用 fgets 还是 fscanf 以及如何在我的数组的每一行中写下每个单词。
int file_string_temp_number_rows=200;
int file_string_temp_number_cols=200;
char **file_string_arr = (char**)malloc (file_string_temp_number_rows*sizeof(char));
for ( i = 0 ; i < file_string_temp_number_rows ; i++){
file_string_arr[i] = (char*)malloc(file_string_temp_number_cols*sizeof(char));
}
if ((file_ptr= fopen(filename, "r"))){
if((file_ptr=fopen(filename,"r"))==NULL)
{
printf("errore apertura file");
return 1;
}
else{
while(!feof(file_ptr)){
for(i = 0 ; i < file_string_temp_number_rows ; i++){
for(j = 0 ; j < file_string_temp_number ; j++){
fgets(file_string_arr , 40 , filename);
}
}
}
}
}
}
最佳答案
解决您的标题问题:我如何从文件中读取字符串数组?
有很多方法可以做到这一点。以下是可以使用的基本步骤列表。
1) 使用 fopen() ,打开文件并扫描以确定以下内容:
- 最大字长。
- 文件中的字数。
2) 创建容器:- 使用 calloc() 为单词创建一个字符串数组。
3) 使用 fopen()
(再次), fgets() 和 strtok() (或变体)将文件内容解析为字符串数组。
注意,下面的示例实现片段使用了特定的函数和技术,但您不应将您的实现仅限于这些。有很多方法同样有效,所以不要害怕尝试。例如,fgets()
或 fscanf()
都可以用来解决这个问题。下面突出显示的方法只是完成任务的一种方法的示例。
扫描示例
// provides count of words, and longest word
int longestWord(char *file, int *nWords)
{
FILE *fp=0;
int cnt=0, longest=0, numWords=0;
char c;
fp = fopen(file, "r");
if(fp)
{
// if((strlen(buf) > 0) && (buf[0] != '\t') && (buf[0] != '\n') && (buf[0] != '\0')&& (buf[0] > 0))
while ( (c = fgetc(fp) ) != EOF )
{
if ( isalnum (c) ) cnt++;
else if ( ( ispunct (c) ) || ( isspace(c) ) || (c == '\0' ))
{
(cnt > longest) ? (longest = cnt, cnt=0) : (cnt=0);
numWords++;
}
}
*nWords = numWords;
fclose(fp);
}
else return -1;
return longest;
}
//in main eg:
int longest;
int count;
...
longest = longestWord(".\\file.txt", &count);//longest and count will be
//used to create string arrays
创建字符串数组示例
//Create string arrays to contain words using result from original scan of file
char ** Create2DStr(ssize_t numStrings, ssize_t maxStrLen)
{
int i;
char **a = {0};
a = calloc(numStrings, sizeof(char *));
for(i=0;i<numStrings; i++)
{
a[i] = calloc(maxStrLen + 1, 1);
}
return a;
}
// in main(): Create array of words
char **words = Create2DStr(count, longest);//Using values obtained from scan section above
if(words) { //continue
解析成字符串示例
// in main(), after performing scan and array creation:
const char delim[] = {" \n\t"};
char line[260];
char *buf = NULL;
fp = fopen(".\\file.txt", "r");
cnt=0;
while(fgets(line, 260, fp))//keep reading lines until EOF
{
buf = strtok(line, delim);
while(buf)//continue until last word in line is parsed
{
if((strlen(buf) > 0)
{
strcpy(words[cnt], buf);
cnt++; //use as accurate count of words.
}
buf = strtok(NULL, DELIM);
}
}
fclose(fp);
关于c - 如何从文件中读取字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53636581/