首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于文件的读入有关问题

2012-03-11 
关于文件的读入问题,有一文件1.txt,有n行,每行都是由8个任意阿拉伯数字组成,比如12345238,或者87654321等

关于文件的读入问题,
有一文件1.txt,有n行,每行都是由8个任意阿拉伯数字组成,比如12345238,或者87654321等等,请问各位大侠,可以采用什么方式,每次八个数字的读入数字串?

[解决办法]
#include <iostream>
#include <fstream>
using namespace std;

void main()
{
fstream ifile( "文件路径 ");
while(!ifile.fail())
{
char ch;
ifile.get(ch);
if(!ifile.eof())
cout < <ch;
}
cout < <endl;
}
[解决办法]
对于txt格式的文件,经常会出现死循环。
[解决办法]
8位没有超过int的范围,对于任意一行:
如果要8位按一个数处理,可以用整型读
如果要按8个数读可以读入字符数组
[解决办法]
getline
[解决办法]
void main()
{
FILE* pFile=fopen( "1.txt ", "r ");
fseek(pFile,0,SEEK_END);
int len=ftell(pFile);
char *pBuf;
pBuf=new char[len];

fseek(pFile,0,SEEK_SET);
fread(pBuf,1,len,pFile);
cout < <pBuf;

}
[解决办法]
char buf[10];
fp = fopen( "a.txt ", "r ");
while( fgets(buf, 8, fp) != NULL )
{
printf( "buf = %s\n ", buf);
}
fclose( fp );
[解决办法]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
FILE *file;
int count=10;
char *p;
char *buf=(char *)malloc(sizeof(char)*9);
file=fopen( "D:\\test\\test.txt ", "rb ");
fgets(buf,9,file);
fseek(file,count,SEEK_SET);
printf( "%s\n ",buf);
while(1)
{
p=fgets(buf,9,file);
if(p==NULL)
break;
printf( "%s\n ",buf);
count+=10;
fseek(file,count,SEEK_SET);
}
free(buf);
fclose(file);
}
测试通过^_^
[解决办法]
测试文件内容:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345
90123456
01234567
打印内容:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345
90123456
01234567
不仅限於数字,字符也可以。
[解决办法]
楼上的,不需要特意使用malloc吧

字符串数组就能满足要求的时候,干嘛非要特意用MALLOC

热点排行