本文介绍了阅读一个txt文件fscanf vs. fread与textscan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从SQL-2005(ANSI格式)生成的.txt文件。我试过 textscan fscanf 。整个txt文件只有数字数据。



在线资源表明fscanf比textscan更快,但是我发现它除此以外。


  • 文本扫描比fscanf快得多


    我想用 fread 来试试这个,但我不知道如何使用fread导入数据。你能提出建议/评论吗?

      fName ='Test.txt'%从ANSI格式的SQL,5百万行,5列
    Numofrows = 1000000; %1百万
    Numcols = 5;

    fid = fopen(fName,'r');
    C = textscan(fid,'%f%f%f%f%f',Numofrows);
    C = cell2mat(C);

    fclose(fid); fid = fopen(fName,'r');
    [C,Count] = fscanf(fid,'%f%f%f%f%f',Numofrows * Numcols);
    C =重塑(C,Count./Numofrows,Numofrows); C = C;


    解决方案

    还有另外一个选项, code> load

      L = load(fName); 

    这很简单,并且会自动为您计算出格式。它有一些限制 - 格式应该有相同数量的每行。


    I have a .txt file that has been generated from SQL-2005 (in ANSI format). I have tried textscan and fscanf. The entire txt file has only numeric data.

    Online resources suggest that fscanf is FASTER than textscan but I found it otherwise.

    • Textscan was much faster than fscanf

    I want to try this with fread as well but I do not know how to import data using fread. Can you please suggest/comment? Thanks.

    fName     = 'Test.txt'    % From SQL in ANSI format, 5million rows, 5 Cols
    Numofrows = 1000000 ; %1million
    Numcols   = 5 ;
    
    fid = fopen(fName, 'r');
    C   = textscan(fid, '%f %f %f %f %f', Numofrows ) ;
    C   = cell2mat(C);
    
    fclose(fid); fid = fopen(fName, 'r');
    [C, Count] = fscanf(fid, '%f %f %f %f %f', Numofrows * Numcols ) ;
    C = reshape(C, Count./Numofrows , Numofrows ) ; C=C';
    
    解决方案

    There is another option that you did not list: load

       L = load(fName);
    

    It is very simple, and will figure out the format automatically for you. It does have some limitations - The format should have same amount of numbers in each line.

    这篇关于阅读一个txt文件fscanf vs. fread与textscan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 00:54