cread(creade热水壶)

http://www.itjxue.com  2023-01-30 00:04  来源:未知  点击次数: 

C中read函数读取问题

read函数里有这样一句话 infilep1-gradeshuzu[i];,你的目的应该是要把文件中的数逐个存入到gradeshuzu数组中。但是实际上这句话并不能完成这个任务。你可以单步调试到这句话,程序就会出错。

gradeshuzu是一个vector,因此不能直接像这样直接写入。应该采用类似这样的一段代码:

vectorint a;

void main()

{

for(int i=0;i10;i++)

a.push_back(i); //a此时等同于一个 int [10]数组

}

因此你的程序应该这样修改一下:

for(i=0;isize;i++)

{

// infilep1-gradeshuzu[i];

float temp;

infiletemp;

p1-gradeshuzu.push_back(temp);

coutp1-gradeshuzu[i];

}

有关vector的使用可参见我的文章

C中read()的用法?

read()函数的原型是int read(int fd,void *buf,int count);。它的功能是“从文件说明符fd相关联的文件中读取count个字符,并把这些字符存储到buf所指的缓冲区中。返回值是操作成功时所读到的字节数,在文件结束时可能少于count个字节;若返回值为-1则说明出错了,返回0则表示到达文件尾端。例:从文件ABC.txt中读取前100个字节存入数组buffer中——

#include "stdin.h"

#include "io.h"

#include "fcnt1.h"

int main(void){

int fd;

char buffer[100];

if((fd=open("ABC.txt",O_RDONLY))==-1){

printf("Can't open file.\n");

exit(-1);

}

if(read(fd,buffer,100)!=100)

printf("Possible read error!\n");

}

C语言read函数

read内部是调_read, _read的返回值在msdn中有这样的描述

_read returns the number of bytes read, which might be less than count if there are fewer than count bytes left in the file or if the file was opened in text mode, in which case each carriage return–line feed (CR-LF) pair is replaced with a single linefeed character. Only the single linefeed character is counted in the return value. The replacement does not affect the file pointer.

注意这一段: in which case each carriage return–line feed (CR-LF) pair is replaced with a single linefeed character

就是说如果用text模式打开的话, 文件换行时可能在文本中有2个字符----换行和缩进(CR-LF), 而在return的时候系统是把它作为1个回车符号('\n')所返回的. 所以会导致这个情况

C中的read在什么情况下读到空文件会等待,什么时候读到空文件会直接返回错误?

如果是文件中的read(),那么,只要执行了这个函数,就会立即返回,不会等待的,不管文件是否为空,它都不会等待!

如果是 socket 中的read(),那么,它会一直阻塞在那里,等待数据的接收,直到有数据来,或者超时才会返回!

(责任编辑:IT教学网)

更多

相关linux文章

推荐linux文章