【问题标题】:How do i read an array of strings from a file?如何从文件中读取字符串数组?
【发布时间】:2019-05-07 06:36:11
【问题描述】:

我有一个文件,其中包含由换行符分隔的不同单词。如何读取每个单词并将其存储在字符串数组中? 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);
                        }
                    }
                }   
            }
        }
    }

【问题讨论】:

  • 您的第一个malloc 应该是*sizeof(char *),因为您想为指针分配空间。
  • 还有,为什么要打开文件两次?
  • 我将您的帖子恢复为原始内容。一般来说,使用来自 cmets 或答案的内容来编辑您的帖子以进行更正并不是一个好主意。 (除了格式,或澄清您的问题的附加信息)它导致人们不得不追逐解决方案。也就是说,当您将其他人的建议编辑到您的答案中时,问题就变成了一个移动的目标。

标签: c arrays file input


【解决方案1】:

解决您的标题问题:如何从文件中读取字符串数组?

有很多方法可以做到这一点。这是可以使用的基本步骤的列表。

1) 使用 fopen(),打开文件并扫描以确定以下内容:
- 最大字长。
- 文件中的字数。

2) 创建容器: - 使用 calloc() 为单词创建一个字符串数组。

3) 使用fopen()(再次)、fgets()strtok()(或变体)将文件内容解析为字符串数组。

注意,下面的示例实现 sn-ps 使用特定的功能和技术,但您不应将实现仅限于这些。有许多方法同样有效,所以不要害怕尝试。例如,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);

【讨论】:

  • 您好,感谢您的回答。我能问你最后两个while循环做什么吗? while(buf) 什么时候停止?为什么?
  • @GiacomoMasciarelli - 当看到 NULL 时,两个循环都会退出。具体来说,fgets() 在没有其他内容可读取时返回NULL(即EOF),因此外循环将继续直到它看到NULL。类似地,内部循环也会继续,直到它看到NULL,但在这种情况下,它正在查看strtok() 函数的返回值。我在上面的帖子中包含了这两个函数(fgets()strtok())的链接。一定要看看他们两个,特别是阅读他们的return类型。
  • mb 我不知道 NULL 会在循环时自动结束,谢谢
  • @GiacomoMasciarelli - 欢迎您。是的,只要conditionTRUEwhile(condition){...} 构造就会继续循环。只要condition 变为FALSE,它就会退出构造。 NULL 根据定义计算为 FALSE。顺便说一句,感谢您的接受!
  • char c; 应该是 int c;,否则 EOF 检测可能不起作用。
猜你喜欢
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多