更新时间:2015-11-25 23:38:37浏览次数:1+次
我们读取这样的一个文件:
普通的读取操作代码:
#include "stdio.h"
#include "windows.h"
#include "process.h"
FILE *stream, *stream1;
int main(void)
{
errno_t err;
char ch;
// Open for read (will fail if file "in1.txt" does not exist)
if ((err = fopen_s(&stream, "in.txt", "r")) != 0)
{
printf("The file 'in.txt' was not opened\n");
//Sleep(3000);
}
else
{
printf("The file 'in.txt' was opened\n");
//Sleep(3000);
}
// Open for write
if ((err = fopen_s(&stream1, "temp.txt", "w")) != 0)
{
printf("The file 'temp.txt' was not opened\n");
//Sleep(3000);
}
else
{
printf("The file 'temp.txt' was opened\n");
//Sleep(3000);
}
while ((ch = getc(stream)) != EOF)
{
//putchar(ch);
fputc(ch, stream1);
}
fclose(stream);
fclose(stream1);
system("pause");
return 0;
}
代码执行结果:
原来的969k只读出来了107k,反正没有读完!下面我们试试二进制读取:
#include "stdio.h"
#include "windows.h"
#include "process.h"
FILE *stream, *stream1;
int main(void)
{
errno_t err;
char ch;
// Open for read (will fail if file "in1.txt" does not exist)
if ((err = fopen_s(&stream, "in.txt", "rb")) != 0)///b代表以二进制流读取文件
{
printf("The file 'in.txt' was not opened\n");
//Sleep(3000);
}
else
{
printf("The file 'in.txt' was opened\n");
//Sleep(3000);
}
// Open for write
if ((err = fopen_s(&stream1, "tempB.txt", "wb")) != 0)///b代表以二进制流写入文件
{
printf("The file 'tempB.txt' was not opened\n");
//Sleep(3000);
}
else
{
printf("The file 'tempB.txt' was opened\n");
//Sleep(3000);
}
while ((ch = getc(stream)) != EOF)
{
//putchar(ch);
fputc(ch, stream1);
}
fclose(stream);
fclose(stream1);
system("pause");
return 0;
}
装逼成功!不过为了安全起见,我还是建议你利用宽字符集来读取!因为语言的多样性!
看代码:
#include "stdio.h"
#include "windows.h"
#include "process.h"
FILE *stream, *stream1;
int main(void)
{
errno_t err;
char ch;
// Open for read (will fail if file "in1.txt" does not exist)
if ((err = _wfopen_s(&stream, L"in.txt", L"rb")) != 0)///_wopen_s代表以二进制流宽字符形式读取文件
{
printf("The file 'in.txt' was not opened\n");
//Sleep(3000);
}
else
{
printf("The file 'in.txt' was opened\n");
//Sleep(3000);
}
// Open for write
if ((err = _wfopen_s(&stream1, L"WtempB.txt",L"wb")) != 0)///_wopen_s代表以二进制流宽字符形式写入文件
{
printf("The file 'WtempB.txt' was not opened\n");
//Sleep(3000);
}
else
{
printf("The file 'WtempB.txt' was opened\n");
//Sleep(3000);
}
while ((ch = getc(stream)) != EOF)
{
//putchar(ch);
fputc(ch, stream1);
}
fclose(stream);
fclose(stream1);
system("pause");
return 0;
}
图:
你或许注意到了,这个文件的大小远比969k大,这是用宽字符读取的正常结果,因为一个宽字符是两个字节!当我们不知道文件里面有什么时,为了安全起见,还是用宽字符读取好!就因为语言文字的多样性。谁知道一个文件里面有没有阿拉伯语,德文,法文....
相关资讯