2013-07-09 79 views
0

我写了下面的代码从“FILE.DAT”读书读()函数中使用读取功能无法读取通过在C

#include<stdio.h> 

int main() 
{ 
    int fd,xr; 
    char b; 
    if ((fd=open("file.dat"))==-1) 
    { 
    puts("Cannot open file"); 
    exit(0); 
    } 
    else 
    { 
    puts("File opened successfully"); 
    } 
    puts("Trying to read"); 
    do 
    { 
    xr = read(fd,b,1); 
    printf("%s",b); 
    } while(xr!=-1) 
    close(fd); 
} 

文件FILE.DAT包含字符串“你好”,但我我得到一些垃圾字符作为输出。什么是错误?的b

+1

printf(“%c”,b); 试试这个.....否则试试这个char b [1]; – Gangadhar

+2

此代码写得很差,很难知道从哪里开始。查看您在Google'C read example'中找到的许多发布示例中的一个。以下仅供初学者参考:http://ubuntuforums.org/showthread.php?t=1103327 – Gene

+0

Manoj首先缩进您的代码 –

回答

3
  1. 通地址read()xr = read(fd,&b,1);

  2. 使用%c,而不是%s打印:printf("%c",b);

0

printf()格式的说,你要打印一个字符串,要求您为printf()提供一个指向字符的指针(字符序列被认为是空终止)。但是,您仅向printf()提供了一个字符,然后将它视为指针。

0

尝试做:

printf("%c",b); 

代替

printf("%s",b); 

,因为%s需要要传递一个空终止字符数组(又名C-字符串)

0

你给的printf一个字符但指定您想要打印一个字符串。因此,它打印开始在B点的所有字节,直到遇到一个空结尾的\ 0,这大概是你的 “垃圾”

0
  1. 尝试: *的printf( “%C”,B); *,因为您在do-while中读取了一个字符{}
  2. 并且将b的地址传递给read(),因为xr = read(fd,& b,1);