【问题标题】:getline() reading garbage value while reading from a text filegetline() 从文本文件读取时读取垃圾值
【发布时间】:2020-10-27 07:08:33
【问题描述】:

在下面的代码中,我想读取第一行为<p> -> <many_declaration> <many_expression> 的文本文件。代码sn-p如下:

    ssize_t read;
size_t len = 200;
FILE *fptr;
fptr = fopen(fn ,"r");


if(fptr==NULL){
    printf("Error\n");
    fclose(fptr);
}

else{
    int line_number=1;

    char * line = (char *)malloc(sizeof(char)*200);
    while((read = getline(&line, &len, fptr)) != -1)
    {
        char * tokens = strtok(line, " \t\n");
        
        
        while( tokens != NULL ) 
        {
            
            printf("%s \n",tokens);
            printf("%zu \n",strlen(tokens));
            
            tokens = strtok(NULL, " \t\n");
            
        }
        

    }
}

但是,在使用getline() 读取它,然后使用strtok() 拆分字符串时,第一个标记应该是大小为 3 的<p>,但正在读取的字符串是一些不可见的字符,后跟<p> 和长度是 6。你能告诉我问题是什么吗?谢谢!

【问题讨论】:

标签: c getline garbage


【解决方案1】:

文件可能以 UTF8 BOM 开头。如果是这样,您应该以 UTF-8 格式读取文件。

【讨论】:

  • 这是我使用 sublime 创建的文本文件,我如何知道它是否以 UTF BOM 开头?
  • superuser.com/a/581554/66154 -- 文件的保存方式决定了您应该如何解释 c 中的字符。不要假设“char”与文本字符相同。这仅适用于以 7 位 ASCII 编码的文本,不包括世界上的大多数文本。另见:joelonsoftware.com/2003/10/08/…
猜你喜欢
  • 2016-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2011-06-26
相关资源
最近更新 更多