文件输出

mz126 2015-05-18 03:02:07
求大神知道 为什么10之前的数无法正常打出

/* 将 1 - 100 写入文件 然后倒序读出来 */

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE* pfile = NULL;
int val = 0;
long cnt = 0L;
int i = 0;

// open the file
pfile = fopen( "abc.txt" , "w" );
if( !pfile )
{
fprintf( stderr , "can not open the file \n" );
exit( 1 );
}

// write the file
for( val = 1 ; val <= 100 ; ++ val )
{
fwrite( &val , sizeof( int ) , 1 , pfile );
}

// close the file
fclose( pfile );

// open the file
pfile = fopen( "abc.txt" , "r" );

for( i = 1 ; i <= 100 ; ++ i )
{
fseek( pfile , - i * sizeof( int ) , SEEK_END );
fread( &val , sizeof( int ) , 1 , pfile );
printf( "%d " , val );
if( i % 10 == 0 ) printf( "\n" );
}

// close the file
fclose( pfile );

return 0;
}
...全文
119 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
youjun610789338 2015-05-18
  • 打赏
  • 举报
回复
我能说,我只是copy了你的代码然后在Linux下g++编译后运行,没有出现你描述的现象吗


另外,1楼我想问问,你确定Linux用gcc能编译通过吗,我用gcc编译报如下错误:
/tmp/ccGpl1qQ.o:(.eh_frame+0x12):对‘__gxx_personality_v0’未定义的引用
collect2: ld 返回 1
苏叔叔 2015-05-18
  • 打赏
  • 举报
回复

100 99 98 97 96 95 94 93 92 91 
90 89 88 87 86 85 84 83 82 81 
80 79 78 77 76 75 74 73 72 71 
70 69 68 67 66 65 64 63 62 61 
60 59 58 57 56 55 54 53 52 51 
50 49 48 47 46 45 44 43 42 41 
40 39 38 37 36 35 34 33 32 31 
30 29 28 27 26 25 24 23 22 21 
20 19 18 17 16 15 14 13 12 11 
10 9 8 7 6 5 4 3 2 1 
苏叔叔 2015-05-18
  • 打赏
  • 举报
回复
若使用fwrite和fread,请使用"~b"的模式打开文件 修改如下:

/*  将 1 - 100 写入文件 然后倒序读出来 */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	FILE* pfile = NULL;
	int val = 0;
	long cnt = 0L;
	int i = 0;

	// open the file
	//pfile = fopen("abc.txt", "w");
	pfile = fopen("1.txt", "wb");
	if (!pfile)
	{
		fprintf(stderr, "can not open the file \n");
		exit(1);
	}

	// write the file
	for (val = 1; val <= 100; ++val)
	{
		fwrite(&val, sizeof(int), 1, pfile);
	}

	// close the file
	fclose(pfile);

	// open the file
	pfile = fopen("1.txt", "rb");

	for (i = 1; i <= 100; ++i)
	{
		fseek(pfile, -i * sizeof(int), SEEK_END);
		fread(&val, sizeof(int), 1, pfile);
		printf("%d ", val);
		if (i % 10 == 0) printf("\n");
	}

	// close the file
	fclose(pfile);
	return 0;
}
赵4老师 2015-05-18
  • 打赏
  • 举报
回复
电脑内存或文件内容只是一个一维二进制字节数组及其对应的二进制地址; 人脑才将电脑内存或文件内容中的这个一维二进制字节数组及其对应的二进制地址的某些部分看成是整数、有符号数/无符号数、浮点数、复数、英文字母、阿拉伯数字、中文/韩文/法文……字符/字符串、汇编指令、函数、函数参数、堆、栈、数组、指针、数组指针、指针数组、数组的数组、指针的指针、二维数组、字符点阵、字符笔画的坐标、黑白二值图片、灰度图片、彩色图片、录音、视频、指纹信息、身份证信息…… 推荐使用WinHex软件查看硬盘或文件或内存中的原始字节内容。
赵4老师 2015-05-18
  • 打赏
  • 举报
回复
不要把 fopen("...","...");fscanf,fprintf,fgets,fgetc,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待 和 fopen("...","...b");fseek,ftell,fread,fwrite,fgetc,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待 弄混了
赵4老师 2015-05-18
  • 打赏
  • 举报
回复
输出上卷到屏幕外面了吧。我猜。
kakashi0309 2015-05-18
  • 打赏
  • 举报
回复
正常啊 linux gcc 环境下面

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧