交谊舞伦巴基本步教学:c语言基础知识

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/03 17:27:20
fread和fwrite和fgets和fgetc都怎么用啊
最好有实例
我都弄了好几天了
只能往文件里写]
就是读不出来呀
我很着急
还有“r”"a""ar+""w"都什么意思呀
fread(buf, strlen(msg)+1, 1, stream);
strlen(msg)这个可以换成具体的数么
rtn=fread(fh,&state[i],sizeof(state[i]));
这对么
还有就是
如果把stream = fopen("DUMMY.FIL", "w+"))
改成stream = fopen("DUMMY.txt", "w+"))还能行么
还有就是这里都可以写什么
w+不是每次都要新打开一个么
好的
我会了

1 先打开文件
FILE *fp=fopen(文件所在位置,打开方式);
打开方式有:"r"文件只读 "w" 文件只写 "r+" 读写,还有很多就不一一列举了。
2 写入
fputc(ch,fp); ch:要写的字符。
3 读取
ch=fgetc(fp); fp:打开文件时的指针。
以上两个只能一个一个字符的读/写。
4 fread 和 fwrite 可以读入一组数据!
fread(buffer,size,count,fp)
fwrite(buffer.size,count,fp);
size: 指你想以什么为单位来读,如以整形为单位来读那么size=sizeof(int).这样一读就读一个整形的长度。
count:是指读入多少个size的单位。
buffer:是数组的指针。

对于sizeof:它可以计算变量的长度。似乎你想计算数组里一个元素的长度,sizeof(array[i])这样吧,那个size参数完全可以等于一个数字。

读入文件的扩展名叫什么无所谓。

回答的有不足之处,敬请谅解。

Prototype

size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

Description

Reads data from a stream.

fread reads n items of data each of length size bytes from the given input stream into a block pointed to by ptr.

The total number of bytes read is (n * size).

Return Value

On success fread returns the number of items (not bytes) actually read.

On end-of-file or error it returns a short count (possibly 0).

#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *stream;
char msg[] = "this is a test";
char buf[20];

if ((stream = fopen("DUMMY.FIL", "w+"))
== NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}

/* write some data to the file */
fwrite(msg, strlen(msg)+1, 1, stream);

/* seek to the beginning of the file */
fseek(stream, SEEK_SET, 0);

/* read the data and display it */

fread(buf, strlen(msg)+1, 1, stream);
printf("%s\n", buf);

fclose(stream);
return 0;
}