发现自己真的被各种高级语言宠坏了。玩C还真的各种不懂的。
问题
例如下面的代码可以正确输出,但将
ret = readfile (fd, buf, len);
换成
readfile (fd, buf, len);
输出就变乱码了。
不懂啊。(:з」∠)
1#include <stdio.h> 2#include <string.h> 3#include <errno.h> 4#include <sys/types.h> 5#include <sys/stat.h> 6#include <fcntl.h> 7#include <unistd.h> 8 9// ssize_t readfile(int fd, void* vBuf, size_t len){ 10ssize_t readfile(int fd, char* vBuf, size_t len){ 11 char* pBuf = vBuf; 12 ssize_t ret, total; 13 14 while (len != 0 && (ret = read (fd, pBuf, len))!=0){ 15 if (ret == -1){ 16 if (errno == EINTR) 17 continue; 18 perror("read"); 19 break; 20 } 21 len -= ret; 22 pBuf += ret; 23 total += ret; 24 } 25 return total; 26} 27 28int main(){ 29 int fd; 30 //打开文件 31 fd = open ("test.txt", O_RDONLY); 32 if (-1 == fd){ 33 perror("open file failed"); 34 return -1; 35 } 36 char buf[512]; 37 size_t len = 200; 38 ssize_t ret; 39 40 ret = readfile (fd, buf, len); 41 printf("%s\n", buf); 42 return 0; 43} 44
补充
- 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调试一下了