c语言-文件操作(2)
前言
在c语言-文件操作(小试),只是学了如何写入文件和描述了文件的操作模式.1.文件拷贝
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int main(int argc, char *arg[])
{
FILE *pReader = fopen("hello.txt", "r"); //读取hello.txt
if (pReader == NULL)
{
printf("打开文件失败!");
return 0;
}
FILE *pWriter = fopen("hello1.txt", "w"); //写入hello1.txt
if (pWriter == NULL)
{
printf("创建文件失败!");
return 0;
}
char singleChar;
while ((singleChar = fgetc(pReader)) != EOF) //遇到字符EOF跳过
{
fputc(singleChar, pWriter);
}
system("hello1.txt"); //打开hello1.txt文件
return 0;
}
2.获取文件大小
int getFileSize(char *path) //方式一获取文件大小
{
int size = -1;
FILE *pReader = fopen(path, "rb"); //用二进制读取
if (pReader == NULL)
{
return 0;
}
while (!feof(pReader))
{
fgetc(pReader);
size++;
}
fclose(pReader);
return size;
}
int getFileSizeForSeek(char *path) //方式二用fseek和ftell
{
FILE *pReader = fopen(path, "rb");
if (pReader == NULL)
{
return 0;
}
fseek(pReader, 0, SEEK_END); //文件指针移动到末尾
int fileLength = ftell(pReader); //获取文件指针距离起始地址的长度
fclose(pReader);
return fileLength;
}
3.文本文件和二进制文件的区别
测试代码
#include <stdio.h>
#include <stdlib.h>
void showTxt(char *path) //以二进制方式读取文件输出
{
FILE *pWriter = fopen(path, "rb");
if (pWriter == NULL)
{
return;
}
int singleChar; //使用int类型接收读取的单个字符避免字符溢出
while ((singleChar = fgetc(pWriter)) != EOF)
{
printf("%4d", singleChar); //打印字符的ascii值
}
fclose(pWriter);
}
int main(int argc, char *argv[])
{
int i = 0;
FILE *pWriterTxt = fopen("hello", "w"); //文本方式写入文件
FILE *pWriterBinary = fopen("helloBinary", "wb"); //二进制方式写入文件
if (pWriterTxt == NULL || pWriterBinary == NULL)
{
printf("create file is failed!\n");
return 0;
}
for (i = 0; i < 5; i++)
{
fputc('\n', pWriterTxt); //文本写入
fputc('\n', pWriterBinary); //二进制写入
}
fclose(pWriterTxt);
fclose(pWriterBinary);
printf("txt:");
showTxt("hello");
printf("\nbinary:");
showTxt("helloBinary");
printf("\n");
system("pause");
return 0;
}
window和linux效果


文本文件和二进制文件对比
- linux系统上,文本和二进制文件的写入是没有区别的
- window上,文本在写入'\n'(ascii码为10),用二进制读取分别13 10(ascii码为'\r' '\n')可见在写入的系统将'\n'进行转换了
- 在二进制写入和读取,Windows和Linux没有区别
结论
Windows系统在读取文本文件 将\r\n转换为\n
Windows写入文本文件 将\n转化为\r\n
秋风
2016-07-10