【问题标题】:Trying to use freopen but for two different files尝试使用 freopen 但用于两个不同的文件
【发布时间】:2014-07-20 18:41:39
【问题描述】:

我正在尝试使用freopen() 打印到两个不同的文件。 有可能吗?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: @"sensordata.txt"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:docDir])
{
    [fileManager createFileAtPath:docFile contents:nil
                                   attributes:nil];
}
freopen([docFile cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
NSLog(@"GyroData: %f %f %f ",gyroData.rotationRate.x, gyroData.rotationRate.y, gyroData.rotationRate.z);


NSLog(@"DeviceMotion: %f  ",magnitude);

第二个 NSLog (DeviceMotion...) 应该保存在另一个文件中。

有什么想法吗? 谢谢

【问题讨论】:

  • 您的问题不清楚。您期望发生的具体情况是什么?实际发生了什么,它与您的预期有何不同?如果您希望对stderr 的写入同时发送到两个文件,那么,不,这不可能按照您的意思。
  • 如果你想这样做,然后转储 NSLog() 并编写你自己的日志框架或使用现有的,比如 CocoaLumberjack:github.com/CocoaLumberjack/CocoaLumberjack

标签: xcode nslog freopen


【解决方案1】:

目前尚不清楚您为什么要这样做。你不能用fprintf 代替吗?对于对象 AFAIK NSLog 只需调用 - (NSString*)description 即可,您可以自己轻松完成。

无论如何,这(可能)是这样的:

NSLog 很可能是直接写入底层STDERR_FILENO 文件描述符(fd)。您可以使用 dup2 系统调用更改该 fd 的目标。

如果您仍想使用FILE* 函数,它看起来像这样(未经测试,需要错误检查):

FILE *newlogfile = fopen([docFile fileSystemRepresentation], "a+");
dup2(fileno(newlogfile), STDERR_FILENO);
fclose(newlogfile);

您不必保留指向文件的指针,因为描述符是重复的。旧的STDERR_FILENO fd 会自动关闭。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
相关资源
最近更新 更多