用fgetc读取文件的后端

[英]C - reading past end of file with fgetc


I have the weirdest thing happening, and I'm not quite sure why it's happening. Basically what I need to do is use fgetc to get the contents of a simple ASCII file byte by byte. The weird part is it worked, but then I added a few more characters and all of a sudden it added a newline that wasn't there and read past the end of the file or something. Literally all I did was

我有最奇怪的事情发生,我不确定为什么会发生。基本上,我需要做的是使用fgetc来获取一个简单的ASCII文件字节的内容。奇怪的是它起作用了,但是我又添加了一些字符,突然它添加了一个不在那里的换行符,并读取了文件的末尾或其他东西。我所做的就是

do {
    temp = (char*) checked_realloc (temp, n+1);
    e = fgetc(get_next_byte_argument);
    temp[n] = e;
    if (e != EOF)
      n++;
 }
while (e != EOF);

And then to check I just printed each character out

然后检查我是否打印了每个字符

temp_size = strlen(temp)-1;
for(debug_k = 0; debug_k < temp_size; debug_k++){
  printf("%c", temp[debug_k]);
}

And it outputs everything correctly except it added an extra newline that wasn't in the file. Before that, I had

它正确地输出所有内容,除了添加了一个不在文件中的新行。在此之前,我有

temp_size = strlen(temp);

But then it ended on some unknown byte (that printed gibberish). I tried strlen(temp)-2 just in case and it worked for that particular file, but then I added an extra "a" to the end and it broke again.

但后来它以某个未知字节(打印出的是胡言乱语)结束。我尝试了strlen(temp)-2,以防万一,它对那个特定的文件起作用,但是我在末尾添加了一个“a”,它又坏了。

I'm honestly stumped. I have no idea why it's doing this.

我真的难住了。我不知道为什么会这样。

EDIT: checked_realloc is just realloc but with a quick check to make sure I'm not out of memory. I realize this is not the most efficient way to do this, but I'm more worried about why I seem to be magically reading in extra bytes.

编辑:checked_realloc只是realloc,但需要快速检查以确保我没有内存不足。我意识到这并不是最有效的方法,但我更担心的是为什么我似乎在用额外的字节神奇地阅读。

2 个解决方案

#1


1  

A safer way to write such operation is:

编写这种操作的更安全的方法是:

  1. memset the memory bulk before use with zeros, if you are allocating memory prior to realloc.And every time you realloc, initialize it to zero.
  2. 如果在realloc之前分配内存,则在使用0之前设置内存块。每次你真正loc的时候,把它初始化为0。
  3. If you are using a memory to access strings or use string functions on that memory always ensure you are terminating that memory with a NULL byte.
  4. 如果您正在使用内存访问字符串或在该内存上使用字符串函数,那么一定要确保使用一个空字节来终止该内存。

do{
    temp = (char*) checked_realloc (temp, n+1);//I guess you are starting n with 0? 
    temp[n]=0;
    e = fgetc(get_next_byte_argument);
    temp[n] = e;
    if (e != EOF)
        n++;
} while (e != EOF);
temp[n]=0;
n=0;

I guess the above code change should fix your issue. You don't need strlen -1 anymore. :)

我想上面的代码更改应该可以解决您的问题。你不再需要strlen -1了。:)

Cheers.

欢呼。

#2


0  

It sounds like you forgot to null terminate your string. Add temp[n] = 0; just after the while.

听起来好像你忘了空结束你的字符串。添加临时[n]= 0;刚过。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/01/18/96bb2d5a25f945151f07d6a90c77700f.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告