可恶的文件读写问题,高手们,拜托了

时间:2008-05-10 05:02:25   来源:论坛整理  作者:  编辑:chinaitzhe
如何在txt文件中写出下面的东西?最好用数组
数字1(long) 字符串1(TCHAR)
数字2(long) 字符串2(TCHAR)
数字3(long) 字符串3(TCHAR)
数字4(long) 字符串4(TCHAR)
.
.
.
.
然后又怎样一次只读一行到数组(最好是读数字用一个数组,读字符串用另一个数组),直到读完呢?


网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



#include <stdio.h>

#include <string.h>



#define MAXN 100



int main()

{

    int i,j,len;

    char num[MAXN];//存入long

    char str[MAXN];//存入字符串

    char line[2*MAXN];

    FILE *fw = fopen("a.in","w");

    if(fw == NULL) 

    {

        printf("open file failed!\n");

        return 0;

    }

    //按行写入文件数据

    fputs("12345abcde\n",fw);

    fputs("1111aaaa\n",fw);

    fclose(fw);

    FILE *fr = fopen("a.in","r");

    if(fr == NULL) 

    {

        printf("open file failed!\n");

        return 0;

    }

    //按行读出文件数据

    while(fgets(line,MAXN*2,fr))//按行读入时读入了'\n'字符

    {

        len = strlen(line);

        for(i = 0, j = 0; i < len;   i)

            if(line[i] >= '0' && line[i] <= '9')

                num[j  ] = line[i];

            else break;

        num[j] = '\0';

        for(j = 0; line[i] != '\n'&&i < len;   i)

            str[j  ] = line[i];

        str[j] = '\0';

        printf("%s %s\n",num,str);

    }

    fclose(fr);

    return 0;

}


输出:
12345 abcde
1111 aaaa
网友回复://写
ofstream output("xxx.txt")
output < <"123456 hello";
output.close();
//读
ifstream input("xxx.txt");
string line;
long num;
string str;
while(getline(input,line)){
stringstream in(line);
in>>num>>str;
cout < <num < <" " < <str < <endl;
}
input.close();
网友回复:前来学习~
正好我也马上要用到这个
网友回复:Thank you!
关键字:可恶,文件,读写,问题,高手,

相关文章

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面