zoukankan      html  css  js  c++  java
  • fopen 中 按文本读写与按二进制读写 实例

    参考:http://blog.csdn.net/hinyunsin/article/details/6401854


    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
    	char he[20] = "hello world\n";
    	
    	FILE *outfile = fopen("t.txt", "wt");
    	fwrite(he, sizeof(char), 20, outfile);
    	fclose(outfile);
    	
    	outfile = fopen("b.txt", "wb");
    	fwrite(he, sizeof(char), 20, outfile);
    	fclose(outfile);
    
    	return 0;
    }

    用WinHex查看本地的两个文件

    t.txt

    b.txt


    可以看到按文本写时 fopen 把 '\n' 替换为了 0D0A


    对应的,读文件时


    #include <stdio.h>
    #include <string.h>
    
    void echo(char *sz)
    {
    	int i = 0;
    	while(sz[i])
    	{
    		printf("%x ", sz[i]);
    		++i;
    	}
    	printf("\n");
    }
    
    int main(int argc, char *argv[])
    {
    	char he[20];
    	
    	FILE *infile = fopen("t.txt", "rt");
    	fread(he, sizeof(char), 20, infile);
    	echo(he);
    	fclose(infile);
    	
    	infile = fopen("b.txt", "rt");
    	fread(he, sizeof(char), 20, infile);
    	echo(he);
    	fclose(infile);
    	
    	infile = fopen("t.txt", "rb");
    	fread(he, sizeof(char), 20, infile);
    	echo(he);
    	fclose(infile);
    
    	infile = fopen("b.txt", "rb");
    	fread(he, sizeof(char), 20, infile);
    	echo(he);
    	fclose(infile);
    
    	return 0;
    }


    第一行,以文本方式打开t.txt,fopen会将0d0a替换为0a

    第二行,以文本方式打开b.txt,返回原内容

    第三行,以二进制方式打开t.txt,fopen不作替换,直接读取0d0a

    第四行,以二进制方式打开b.txt,返回原内容

  • 相关阅读:
    luogu1131 [ZJOI2007]时态同步
    luogu1879 [USACO06NOV]玉米田Corn Fields
    luogu1345 [USACO5.4]奶牛的电信Telecowmunication
    luogu2463 [SDOI2008]Sandy的卡片
    spoj694 DISUBSTR
    luogu2852 [USACO06DEC]牛奶模式Milk Patterns
    poj2217 Secretary 后缀数组
    luogu3809 后缀排序 后缀数组
    hdu4405 Aeroplane chess
    poj2096 Collecting Bugs
  • 原文地址:https://www.cnblogs.com/silyvin/p/9106904.html
Copyright © 2011-2022 走看看