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

问题描述 投票:0回答:1

我已经阅读了很多有关此主题的文档,但是我仍然对此有一些疑问,我知道指针是什么,但是当我尝试使用ı时遇到了一些问题,在下面的代码中,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, char str[], 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);
}
c arrays pointers random return-type
1个回答
0
投票

您重新打开了文件,可能是这种情况。如果文件未关闭则返回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.
}```
© www.soinside.com 2019 - 2024. All rights reserved.