C调用read的乱码问题

发现自己真的被各种高级语言宠坏了。玩C还真的各种不懂的。

问题

例如下面的代码可以正确输出,但将

ret = readfile (fd, buf, len);

换成

readfile (fd, buf, len);

输出就变乱码了。

不懂啊。(:з」∠)

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

// ssize_t readfile(int fd, void* vBuf, size_t len){
ssize_t readfile(int fd, char* vBuf, size_t len){
    char* pBuf = vBuf; 
    ssize_t ret, total;

    while (len != 0 && (ret = read (fd, pBuf, len))!=0){
         if (ret == -1){
            if (errno == EINTR)
                continue;
            perror("read");
            break;
        }
        len -= ret;
        pBuf += ret;
        total += ret;
    }
    return total;
}

int main(){
    int fd;
    //打开文件
    fd = open ("test.txt", O_RDONLY);
    if (-1 == fd){
        perror("open file failed");
        return -1;
    }
    char buf[512];
    size_t len = 200;
    ssize_t ret;

    ret = readfile (fd, buf, len);
    printf("%s\n", buf);
    return 0;
}

补充

  • void*改成char*编译器就不会报warning,但不影响结果
  • 以上问题在ubuntu下发现,换openSUSE没问题(gcc (SUSE Linux) 4.6.2),win7 x64下char buf[512];改成char buf[200];也没问题。
  • ubuntu下将char buf[512];改成 char buf;可以得到正确结果,但同样代码(改char buf)扔到windows下的gcc (tdm64-1) 4.7.1则报异常。扔到openSUSE在perror那行输出Bad Address错误
  • 我要学学gdb调试一下了

你可能感兴趣的:(c,读文件)