问一个读文件的问题

shiplou 2006-10-23 08:04:30
一个文件中:

// the macroblock number is 0!
0000000000000001
0000000100000002
0000000200000003
0000000300000004
0000000400000005
0000000500000006
0000000600000007
0000000700000008
0000000800000009
000000090000000a
// the macroblock number is 10!
0000000a0000000b
0000000b0000000c
0000000c0000000d
0000000d0000000e
0000000e0000000f
0000000f00000010
0000001000000011
0000001100000012
0000001200000013
0000001300000014
// the macroblock number is 20!


有注释行,
也有数据行(一行2个int型数据,共64位)
我想把这些数据读出来存到数组里,注释的行不要(注释行可能随机出现)。
...全文
225 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
shiplou 2006-10-24
  • 打赏
  • 举报
回复
楼上的是什么语言啊?我想用纯C来写。
我的做法用fgets读出一行之后,用memcmp如果能找到字符串首为“//”,就去掉该行
但是数据行用fgets读出来,用atoi转化为整数,值却不对。
jixingzhong 2006-10-24
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <stdio.h>

int main()
{
int a[1024], pos = 0;
char line[256];
FILE *fp = fopen("input.txt", "r");
while (fgets(line, 250, fp))
{
if (line[0] != '/') /* 判断是否注释行 */
{
int x;
sscanf(line + 8, "%x", &a[pos + 1]); /* 读后半截整数 */
line[8] = '\0';
sscanf(line, "%x", &a[pos]); /* 读前半截整数 */
pos += 2;
}
}

for (int i = 0; i < pos; ++i)
printf("%d\n", a[i]);
system("PAUSE");
return 0;
}
Kusk 2006-10-23
  • 打赏
  • 举报
回复
给你写了一下程序。基本思路是每次读入一行,然后判断行首是否是'/'注释符,若是则跳过,
若不是,则将字符串分两段读入数组中:

#include <stdio.h>
#include <fstream>

using namespace std;

int main()
{
int a[1024], pos = 0;
char line[256];
ifstream inf("input.txt");
while (inf.getline(line, 250))
{
if (line[0] != '/') /* 判断是否注释行 */
{
int x;
sscanf(line + 8, "%x", &a[pos + 1]); /* 读后半截整数 */
line[8] = '\0';
sscanf(line, "%x", &a[pos]); /* 读前半截整数 */
pos += 2;
}
}

for (int i = 0; i < pos; ++i)
printf("%d\n", a[i]);
return 0;
}
飞哥 2006-10-23
  • 打赏
  • 举报
回复
你可以按行读入数据
比如说
gets(fp,64,buffer);buffer是一个字符数组
然后用strstr来查找是否存在"\\\\"两个斜杠
如果存在就不仅行处理

否则就是你要的数据行
存起来

69,382

社区成员

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

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