分割错误读取文本的随机行?

我已经阅读了很多有关此主题的文档,但是我仍然对此有一些疑问,我知道指针是什么,但是当我尝试使用ı时遇到了一些问题,在下面的代码中,txt文件每个单词仅包含一个单词我尝试从文本中读取随机行并在需要时返回主函数)。然后在主函数中打印它,请您能帮我更改此代码的哪一部分?(当我尝试运行此错误消息是分段错误(核心已转储))

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char word(char *file,char str[],int i);

int main() {
  char buf[512];

  char j = word("words.txt",buf,512);
  puts(j); // print random num
}

char word(char *file,int i) {
  int end,loop,line;

  FILE *fd = fopen(file,"r");
  if (fd == NULL) {
    printf("Failed to open file\n");
    return -1;
  }

  srand(time(NULL));
  line = rand() % 100 + 1; // take random num

  for (end = loop = 0; loop < line; ++loop) {
    if (0 == fgets(str,sizeof(str),fd)) { // assign text within a random line to STR
      end = 1;
      break;
    }
  }
  if (!end)
    return (char*)str; // return the str pointer
  fclose(fd);
}
cmsad 回答:分割错误读取文本的随机行?

您可能重新打开了文件。如果文件未返回fd的if(!end)部分,则不关闭文件。 该函数使用char但实际上需要char *

char word(char *file,char str,int i);

int main() {
  char * buf = malloc(sizeof(char)*512);
  char *words = "words.txt";
  char* j = word(words,buf,512);
  puts(j); // print random num
}

char word(char *file,char str[],int i) { // FIX HERE
  int end,loop,line;

  FILE *fd = fopen(file,"r"); // 
  if (fd == NULL) {
    printf("Failed to open file\n");
    return -1;
  }

  srand(time(NULL));
  line = rand() % 100 + 1; // take random num

  for (end = loop = 0; loop < line; ++loop) {
    if (0 == fgets(str,sizeof(str),fd)) { // MAIN PROBLEM,PUT A CHAR* TO STR. 
      end = 1;
      break;
    }
  }
fclose(fd); // YOU DIDN'T CLOSE IF IT RETURNED BEFORE
  if (!end)
    return str; // return the str pointer

//NOTHING IS RETURNED HERE
return str;
// I guess the problem is here,you return nothing and the function finishes,and you try to write that nothing with puts function which may cause a seg fault.
}```
本文链接:https://www.f2er.com/2449749.html

大家都在问