read()调用后,Printf打印垃圾.偏移量始终打印为0 [英] Printf printing garbage after read() call. The offset is always printed as 0

查看:144
本文介绍了read()调用后,Printf打印垃圾.偏移量始终打印为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdint.h>

int main()
{
    int file;
    off_t offset;

    if((file=open("testfile.txt",O_RDONLY)) < -1)
            return 1;

    char buffer[19];

    if(read(file,buffer,19) != 19)  return 1;
    fprintf(stdout,"%s\n",buffer);


    if(offset = lseek(file,-19,SEEK_END) < 0) return 1;
    fprintf(stdout,"%jd\n",(intmax_t)offset);

    if(read(file,buffer,19) != 19)  return 1;
    fprintf(stdout,"%s\n",buffer);

    return 0;
}

输出如下:

这是一个测试文件.

0

他是一个测试文件

testfile.txt:

testfile.txt :

这是一个测试文件,测试SEEK_END的工作方式,这是一个测试文件

This is a test file Testing how SEEK_END works This is a test file

我尝试了不同的偏移格式,例如%ld,%d,但是输出仍然相同. 无法弄清楚为什么垃圾出现在第一行和最后一行的末尾.请帮忙.

I have tried different formatting for offset, such as %ld,%d, but the output is still the same. Can't figure out why garbage appears at the end of first line and last line. Please help.

推荐答案

您需要为行尾字符'\ 0'留出空间;

You need to leave room for an end of line character, '\0';

因此,先创建char buffer[19]; char buffer[20];,然后再添加buffer[19] = '\0';-请记住,它是从零开始的计数.那它就不应该有垃圾数据.

So make char buffer[19]; char buffer[20]; then also add buffer[19] = '\0'; - remember it's zero based counting. Then it shouldn't have the garbage data.

原因是因为printf不知道字符数组的结尾.因此,它将一直打印,直到在垃圾内存中找到"\ 0"为止.

The reason is because printf doesn't know where the end is of the character array. So it keeps printing until it finds a '\0' in garbage memory.

这篇关于read()调用后,Printf打印垃圾.偏移量始终打印为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆