1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <errno.h> #include <fcntl.h> #include <string> using namespace std; void ivrLog(const char *format, ...) { va_list argptr; char buf[1024 * 2]; va_start(argptr, format); vsprintf(buf, format, argptr); va_end(argptr); struct timeval tv; int iRet = gettimeofday(&tv, NULL); time_t t = tv.tv_sec; tm* local = localtime(&t); char timeBuf[256]; strftime(timeBuf, 254, "[%Y-%m-%d %H:%M:%S", local); sprintf(timeBuf + strlen(timeBuf), ":%d] ", (int)(tv.tv_usec / 1000)); string dispStr = timeBuf; dispStr += buf; printf("%s", dispStr.c_str()); // please ensure /sdcard/Test dir existed first char *logFileName = (char *)"/sdcard/Test/log.txt"; int fd = open(logFileName, O_CREAT|O_WRONLY|O_APPEND, 0666); if (fd != -1) { write(fd, dispStr.c_str(), dispStr.length()); close(fd); } } |
Day: September 19, 2018
Android jni fopen返回NULL而errno为13
除了要在AndroidManifest.xml加
1 2 3 | <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> |
关键是看传给fopen或open的文件路径是否“正确”,比如传入“/storage/6236-6439/down/log.txt”之类的路径会返回NULL,errno为EACCES。
比如传入“/sdcard/Test/log.txt”之类的路径则一切正常没任何问题。
如果还是没看到文件被创建,那就该好好看看该jni库是否被正确加载了。