51Testing软件测试论坛

标题: 如何将文件中的字符串读出来 [打印本页]

作者: duola1119    时间: 2008-7-24 13:07
标题: 如何将文件中的字符串读出来
testdata.txt文件中的内容为:
blackdog
rockandrool
thebattleofevermore
stairwaytoheaven
mistymountainhop
我要用LR的方法从文件中读出来。但尝试了很多方法都不行。
代码:
action {
char myfile,loannumber;
int i;
char filename[]="G:\testdata.txt";
myfile=(char)fopen(filename,"r");
for(i=1;i<5;i++)
{
   fscanf(myfile,"%s",loannumber");
   lr_out_message("loannumber %d: %s",i,loannumber);
}
}
但是执行起来却不对,提示内存错误。
这有个例子是个文件loaddata里的内容为
11111
22222
33333
44444
55555
代码:
actions{
  int myfile,loannumber,i;
  char filename[80]="G:\\loaddata.txt";
  myfile=(int)fopen(filename,"r");
  for(i=1;i<5;i++)
   {
     fscanf(myfile,"%D",loannumber);
     lr_out_message("loannumber %d: %d",i,loannumber);  
   }
}
文件里为数字的可以读出来,但文件是里字符串的就读不出来,真是烦死了。还请教高人指点。
作者: duola1119    时间: 2008-7-24 13:42
自己又琢磨了一下。想出来了。
char *filename="G:\\loaddata.txt";
Action()
{
        long file;
        int i;
        char s[32];
        if((file=fopen(filename,"r"))==NULL)
        {
                lr_output_message("file is not exist");
                return -1;
        }
        for(i=0;i<5;i++)
        {
        fscanf(file,"%s",&s);
        lr_output_message("%s",s);
        }
        fclose(file);
        return 0;
}
作者: duola1119    时间: 2008-7-24 13:44
读字符串的文件一定注意声明读文件的变量类型为long的。
作者: 断寒    时间: 2008-7-24 14:01
学习了,我记得以前我写过一段代码把需要的内容写到本地文件的.
LZ把FOR那段代码可以重新考虑一下,那是建立在知道有文件内容有多少行的基础之上,建议可以做个非空行判断自动读取.
读出内容的我用JAVA也写了个.
            try{
            
            String rs ="";
            int rsCount=0;
            DataInputStream file = new DataInputStream(new BufferedInputStream(new FileInputStream("D:\\sql.txt")));
            BufferedReader inbr = new BufferedReader(new InputStreamReader(file));
            while((rs = inbr.readLine()) != null){
                    rsCount++;   
                    System.out.println(rsCount + ":" + rs);   
                }
            }catch   (Exception   e)   {   
          System.out.println("IOException   error!");   
          e.printStackTrace();
            }
JAVA环境有点问题,没有编译,大概看看吧

[ 本帖最后由 断寒 于 2008-7-24 14:15 编辑 ]
作者: duola1119    时间: 2008-7-24 16:09
从loaddata.txt读出内容写入到loaddata1.txt
char *filename="G:\\loaddata.txt";
char *filename1="G:\\loaddata1.txt";
long file,file1;
char s[32];
int i;
Action()
{
        if((file=fopen(filename,"r"))==NULL)
                {
                        lr_output_message("file is not exist!");
                        return -1;
                }
        file1=fopen(filename1,"w");
        for(i=0;i<5;i++)
        {
        fscanf(file,"%s",&s);
        lr_output_message("%s",s);
        fprintf(file1,"%s\n",&s);
        }
                     fclose(file);
                     fclose(file1);
        return 0;
}




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2