试图读取整个文本文件
Trying to read the whole text file
我试图读取整个文本文件,不是逐行,而是整个包含
在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
}
我正在尝试打印文件的整个内容,如:
- 东西…
- 东西…
- 等等…
但是它只是打印最后一行到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
的内容——即文件的最后一行。
一次性吞掉整个文件可以工作,但是仍然存在几个问题:
- 文本字段不是用来显示多行。无论您如何读取文件,您仍然将其内容放在不是为此类内容设计的位置。
- 如果文件足够大,读取它将花费大量时间。如果你在主线程中这样做,那么在这段时间内,应用程序将被挂起。
一个合适的解决方案是:
- 使用文本视图,而不是文本字段。文本视图是为任何行数的文本而构建的,当你在nib中创建一个文本时,它会免费包裹在滚动视图中。
- 一次读取文件一行或其他有限大小的块,但不是在
for
或while
循环中读取。使用NSFileHandle或dispatch_source
,它们都会在读取文件的另一个块时调用你提供的块。 - 将每个块附加到文本视图的存储中,而不是用它替换整个文本。
- 开始阅读时显示进度指示器,完成阅读时隐藏进度指示器。为了获得额外的荣誉,让它成为一个确定的进度条,向用户显示您已经完成了文件的进度。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入