IO接口 2月5日学习笔记

时间:2024-04-16 07:31:29

1.fgetc 

        用于从文件中读取一个字符,fgetc 函数每次调用将会返回当前文件指针所指向的字符,并将文件指针指向下一个字符。


     int fgetc(FILE *stream);

      功能:
        从流中读取下一个字符
      参数:
        stream:文件流指针
      返回值:
        成功返回读到字符的ASCII码值
        失败返回EOF
        读到文件末尾返回EOF

#include <stdio.h>

int main(void)
{
	FILE *fp = NULL;
	char ch = 0;

	fp = fopen("file.txt", "r");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}
	
	while (1)
	{
		ch = fgetc(fp);
		if (EOF == ch)  // 读到末尾退出循环
		{
			break;
		}
		printf("ch = %c\n", ch);
	}

	fclose(fp);

	return 0;
}

统计文件的行数   
 

#include <stdio.h>

int main(void)
{
	FILE *fp = NULL;
	char ch = 0;
	int cnt = 0;

	fp = fopen("file.txt", "r");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}

	while (1)
	{
		ch = fgetc(fp);
		if (EOF == ch)
		{
			break;
		}

		if ('\n' == ch)
		{
			cnt++;
		}
	}

	fclose(fp);

	printf("cnt = %d\n", cnt);

	return 0;
}

  2.fgetc/fputc与getchar/putchar的区别


        char ch = 0;
        ch = getchar();
        ch = fgetc(stdin);

        char ch = 'a'
        putchar(ch);
        fputc(ch, stdout);

fgetc 和 fputc 主要用于文件操作,需要指定文件流作为参数;而getchar 和 putchar 主要用于标准输入输出,直接与控制台交互,不需要额外指定文件。

实现将一个文件中的内容拷贝到另一个文件中

#include <stdio.h>

int main(void)
{
	FILE *fsrc = NULL;
	FILE *fdst = NULL;
	char tmp = 0;

	fsrc = fopen("src.txt", "r");
	if (NULL == fsrc)
	{
		perror("fail to fopen");
		return -1;
	}

	fdst = fopen("dst.txt", "w");
	if (NULL == fdst)
	{
		perror("fail to fopen");
		return -1;
	}

	while (1)
	{
		tmp = fgetc(fsrc);
		if (EOF == tmp)
		{
			break;
		}
		fputc(tmp, fdst);
	}

	fclose(fsrc);
	fclose(fdst);

	return 0;
}

    3.fputs

         int fputs(const char *s, FILE *stream);
      功能:
        向流中写入一个字符串
      参数:
        s:字符串首地址
        stream:文件流指针
      返回值:
        成功返回非负数
        失败返回EOF

#include <stdio.h>

int main(void)
{
	FILE *fp = NULL;
	char str[32] = {"hello world"};

	fp = fopen("file.txt", "w");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}

	fputs(str, fp);

	fclose(fp);

	return 0;
}

    4.fgets

 char *fgets(char *s, int size, FILE *stream);
      功能:
        从流中读取一个字符串
      参数:
        s:存放字符串空间首地址
        size:最多读取字符的个数
        stream:文件流指针
      返回值:
        成功返回存放字符串空间的首地址
        失败返回NULL
        读到文件末尾返回NULL

#include <stdio.h>

int main(void)
{
	FILE *fp = NULL;
	char tmpbuff[3] = {0};
	
	fp = fopen("file.txt", "r");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}

	fgets(tmpbuff, sizeof(tmpbuff), fp);
	printf("tmpbuff = %s\n", tmpbuff);

	fclose(fp);

	return 0;
}

        gets和fgets区别:
        1.gets没有给定最多读取字符的个数,有越界风险
          fgets需要给定最多读取的字符个数,没有越界风险
        2.gets会去掉从终端接收的\n字符,换成\0字符
          fgets会保留从终端接收的\n字符,并在其末尾加入\0

        puts和fputs的区别
        1.puts会在字符串末尾多打印一个\n字符 
        2.fputs不会在末尾多打印\n字符

拷贝文件中的内容

#include <stdio.h>

int main(void)
{
	FILE *fsrc = NULL;
	FILE *fdst = NULL;
	char tmpbuff[4096] = {0};
	char *pret = NULL;

	fsrc = fopen("src.txt", "r");
	if (NULL == fsrc)
	{
		perror("fail to fopen");
		return -1;
	}

	fdst = fopen("dst.txt", "w");
	if (NULL == fdst)
	{
		perror("fail to fopen");
		return -1;
	}
	
	while (1)
	{
		pret = fgets(tmpbuff, sizeof(tmpbuff), fsrc);
		if (NULL == pret)
		{
			break;
		}
		fputs(tmpbuff, fdst);
	}

	fclose(fsrc);
	fclose(fdst);

	return 0;
}


5.fwrite 


      size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
      功能:
        向流中写入nmemb个对象,每个对象size字节大小,在ptr指向的空间中
      参数:
        ptr:存放数据空间的首地址
        size:每个数据对象的大小
        nmemb:数据对象的个数
        stream:文件流指针
      返回值:
        成功返回写入对象的个数
        失败返回0
        读到文件末尾返回0 

#include <stdio.h>

typedef struct student 
{
	char name[32];
	char sex;
	int age;
	int score;
}stu_t;

int main(void)
{
	stu_t a = {"zhangsan", 'm', 19, 100};
	stu_t b = {"lisi", 'f', 18, 90};
	stu_t s[3] = {
		{"zhaowu", 'm', 19, 100},
		{"maliu", 'f', 18, 65},
		{"tianqi", 'm', 17, 90},
	};
	FILE *fp = NULL;

	fp = fopen("file.txt", "w");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}

	fwrite(&a, sizeof(stu_t), 1, fp);
	fwrite(&b, sizeof(stu_t), 1, fp);
	fwrite(s, sizeof(stu_t), 3, fp);

	fclose(fp);

	return 0;
}

   2.fread 
      size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
      功能:
        从流中读取nmemb个对象,每个对象size个字节,存放到ptr指向的空间中
      参数:
        ptr:存放读取内容空间首地址
        size:读取对象的大小
        nmemb:读取对象的个数
        stream:文件流指针 
      返回值:
        成功返回读到对象个数
        失败返回0
        读到文件末尾返回0 

   练习:
        1.利用fread和fwrite完成将src.jpg图片内容拷贝到dst.jpg图片中 
            char tmpbuff[4096];

    3.fprintf 
      int fprintf(FILE *stream, const char *format, ...);
      功能:
        将格式化字符串输出到stream指向的流中

        printf
        fprintf(stdout, );

    4.fsancf 
      int fscanf(FILE *stream, const char *format, ...);
      功能:
        从流中读取格式化的字符串
    
2.流的定位:
    1.ftell
      long ftell(FILE *stream);
      功能:
        获得流的偏移量

    2.rewind
      void rewind(FILE *stream);
      功能:
        将流的偏移量重新设置到开头

    3.fseek 
      int fseek(FILE *stream, long offset, int whence);
      功能:
        设置流的偏移量
      参数:
        stream:文件流指针
        offset:偏移量
            > 0 向后偏移
            < 0 向前偏移
        whence:
            SEEK_SET    文件开头
            SEEK_CUR    文件当前位置
            SEEK_END    文件末尾

#include <stdio.h>

int main(void)
{
	FILE *fp = NULL;

	fp = fopen("file.txt", "w");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}

	fseek(fp, 10, SEEK_SET);
	fputc('a', fp);

	fseek(fp, -5, SEEK_CUR);
	fputc('b', fp);

	fseek(fp, 0, SEEK_SET);
	fputc('c', fp);

	fclose(fp);

	return 0;
}

    练习:从终端输入一个单词,获得单词的含义,格式如下

a                indef art one
abacus           n.frame with beads that slide along parallel rods, used for teaching numbers to children, and (in some countries) for counting
abandon          v.  go away from (a person or thing or place) not intending to return; forsake; desert
abandonment      n.  abandoning
abase            v. ~ oneself/sb lower oneself/sb in dignity; degrade oneself/sb ;
abash            to destroy the self-possession or self-confidence of:disconcert
abashed          adj. ~ embarrassed; ashamed
abate            v. make or become less
abattoir         n. = slaughterhouse (slaughter)
abbess           n. woman who is head of a convent or nunnery
abbey            n.  buildingin which monks or nuns live as a community under an abbot or abbess
abbot            n. man who is head of a monastery or abbey
abbreviate       v. ~ sth shorten (a word, phrase, etc), esp by omitting letters
abbreviation     n.  abbreviating or being abbreviated
abdicate         v.  resign from or formally renounce the throne
abdication       giving up control, authority
abdomen          n.  part of the body below the chest and diaphragm, containing the stomach, bowels and digestive organs
abdominal        adj. in, of or for the abdomen

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

int main(void)
{
	char word[256] = {0};
	char tmpbuff[4096] = {0};
	FILE *fp = NULL;
	char *pret = NULL;
	char *ptmp = NULL;

	gets(word);

	fp = fopen("dict.txt", "r");
	if (NULL == fp)
	{
		perror("fail to fopen");
		return -1;
	}

	while (1)
	{
		pret = fgets(tmpbuff, sizeof(tmpbuff), fp);
		if (NULL == pret)
		{
			break;
		}

		ptmp = tmpbuff;
		while (*ptmp != ' ' && *ptmp != '\0')
		{
			ptmp++;
		}
		*ptmp = '\0';
		ptmp++;
		while (*ptmp == ' ')
		{
			ptmp++;
		}
		
		if (0 == strcmp(tmpbuff, word))
		{
			printf("%s", ptmp);
			fclose(fp);
			return 0;
		}
	}
	
	fclose(fp);
	printf("%s 单词不存在!\n", word);

	return 0;
}

相关文章