使用fgets读取C中的文件

时间:2015-04-16 18:23:59

标签: c fgets

我正在尝试阅读给定的文件,然后将其标记化。我唯一的问题是fgets。文件打开收到没有错误。我在网站的其他地方已经看到了这个,但无论我如何设置它包括将fileLine设置为设定量(如char fileline [200])我得到分段错误。提前感谢您的帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

 int main(int argc, char *argv[]){
    char *fileName = "0";
    char *tokenize, *savePtr;
    struct Record *database= malloc(sizeof(database[0]));
    int recordNum =0;
    char *fileLine = malloc(sizeof(char *));//have replaced with fileline[200] still didnt work
    FILE *fd = open(fileName,O_RDWR);
    if(fd< 0){
        perror("ERROR OPENING FILE");
    }

    while(fgets(fileLine,200,fd) !=NULL){
        printf("%s\n", fileLine);
        tokenize = strtok_r(fileLine,",",&savePtr);
        while(tokenize != NULL){
         //TOKENIZING into a struct
        }
}

3 个答案:

答案 0 :(得分:6)

为什么将open()FILE一起使用?请改用fopen()

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  char *fileName = "test.txt";
  char *tokenize, *savePtr;
  char fileLine[200] = {0}; // init this to be NULL terminated
  FILE *fd = fopen(fileName, "r");
  if (fd == 0) { // error check, equal to 0 as iharob said, not less than 0
    perror("ERROR OPENING FILE");
    return -1;
  }

  while (fgets(fileLine, 200, fd) != NULL) {
    printf("%s\n", fileLine);
    tokenize = strtok_r(fileLine, ",", &savePtr);
    while (tokenize != NULL) {
      tokenize = strtok_r(NULL, ",", &savePtr); // do not forget to pass NULL
      //TOKENIZING into a struct
    }
  }
  return 0;
}

正如Weather Vane所说,如果您使用fd < 0open()会有效。但是,对于fopen(),您应该检查指针是否为NULL,并且是fd == 0


可以在以下位置找到打开文件的这些函数之间的比较:

  1. open and fopen function
  2. C fopen vs open
  3. 我记住的方式是fopen()具有更高的水平。

答案 1 :(得分:1)

这一行

char *fileLine = malloc(sizeof(char *));

char *类型分配内存,4或8个字节(取决于平台)。

所以当你这样做时

fgets(fileLine,200,fd)

它预计会有200字节的可用内存。

试试这个:

char *fileLine = malloc(200);
if (fileLine == NULL) { ... }   // check for error

将分配所需的内存。

答案 2 :(得分:0)

您使用open()代替fopen()

您无法确定该文件是否正确打开,因为fopen()不返回整数,而是指向FILE *对象的指针,如果失败则返回NULL,所以正确的说法是

FILE *file;

file = fopen(filename, "r");
if (file == NULL)
 {
    perror("fopen()");
    return -1;
 }

在您的代码中,即使fgets()失败,您仍然可以使用fopen(),在这种情况下您应该中止该程序。

此外,malloc()将字节数作为大小参数,因此如果您希望将fgets()限制为只读取count个字节,那么malloc()应该是

char  *buffer;
size_t count;

count  = 200; /* or a value obtained someway */
buffer = malloc(count);
if (buffer == NULL)
 {
    fclose(file);
    perror("malloc()");
    return -1;
 }

如果启用编译警告,编译器会指出代码中的所有问题。