试图读取整个文本文件

Trying to read the whole text file

本文关键字:文本 文件 读取      更新时间:2023-10-16

我试图读取整个文本文件,不是逐行,而是整个包含

在xcode 的文本框内打印到屏幕上

我使用obj-c和c++ lang的混合:

while(fgets(buff, sizeof(buff), in)!=NULL){
        cout << buff;  // this print the whole output in the console

         NSString * string = [ NSString stringWithUTF8String:buff ] ;
         [Data setStringValue:string]; // but this line only print last line inside the textfield instead of printing it all
    }

我正在尝试打印文件的整个内容,如:

  1. 东西…
  2. 东西…
  3. 等等…

但是它只是打印最后一行到textfield, please help me

您不使用Obj-C读取文件的原因是什么?它就像这样简单:

NSData *d = [NSData dataWithContentsOfFile:filename];
NSString *s = [[[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding] autorelease];
[Data setStringValue:s];
编辑:要使用你现在拥有的代码,我会尝试这样做:
while(fgets(buff, sizeof(buff), in)!=NULL){
  NSMutableString *s = [[Data stringValue] mutableCopy];
  [s appendString:[NSString stringWithUTF8String:buff]];
  [Data setStringValue:s];
 }

读取文件,以c++字符串形式返回内容:

  // open the file
  std::ifstream is; 
  is.open(fn.c_str(), std::ios::binary);
  // put the content in a C++ string
  std::string str((std::istreambuf_iterator<char>(is)),
                   std::istreambuf_iterator<char>());

在你的代码中,你正在使用C api (FILE*从cstdio)。在C语言中,代码更复杂:

char * buffer = 0; // to be filled with the entire content of the file
long length;
FILE * f = fopen (filename, "rb");
if (f) // if the file was correctly opened
{
  fseek (f, 0, SEEK_END);  // seek to the end
  length = ftell (f);      // get the length of the file
  fseek (f, 0, SEEK_SET);  // seek back to the beginning
  buffer = malloc (length); // allocate a buffer of the correct size
  if (buffer)               // if allocation succeed
  {
    fread (buffer, 1, length, f);  // read 'length' octets
  }
  fclose (f); // close the file
}

要回答为什么你的解决方案不起作用的问题:

[Data setStringValue:string]; // but this line only print last line inside the textfield instead of printing it all

假设Data指向一个文本字段,setStringValue:用您传入的字符串替换该字段的整个内容。您的循环每次读取和设置一行,因此在任何给定时间,string都是文件中的一行。

视图只有在主线程上没有执行任何其他操作时才会被告知显示,因此您的循环(假设您没有在另一个线程或队列上运行它)不会一次打印一行。您读取每一行并用该行替换文本字段的内容,因此当您的循环结束时,该字段将保留最后设置其stringValue的内容——即文件的最后一行。

一次性吞掉整个文件可以工作,但是仍然存在几个问题:

  • 文本字段不是用来显示多行。无论您如何读取文件,您仍然将其内容放在不是为此类内容设计的位置。
  • 如果文件足够大,读取它将花费大量时间。如果你在主线程中这样做,那么在这段时间内,应用程序将被挂起。

一个合适的解决方案是:

  1. 使用文本视图,而不是文本字段。文本视图是为任何行数的文本而构建的,当你在nib中创建一个文本时,它会免费包裹在滚动视图中。
  2. 一次读取文件一行或其他有限大小的块,但不是在forwhile循环中读取。使用NSFileHandle或dispatch_source,它们都会在读取文件的另一个块时调用你提供的块。
  3. 将每个块附加到文本视图的存储中,而不是用它替换整个文本。
  4. 开始阅读时显示进度指示器,完成阅读时隐藏进度指示器。为了获得额外的荣誉,让它成为一个确定的进度条,向用户显示您已经完成了文件的进度。