1. 程式人生 > >JNI中新建檔案、讀寫普通檔案和驅動檔案的方法綜述fopen/open/creat/

JNI中新建檔案、讀寫普通檔案和驅動檔案的方法綜述fopen/open/creat/

這段時間的JNI開發中發現,在JNI中,普通檔案的新建、讀寫既可以用C庫函式,也可以用linux系統函式,如下:

平臺android 4.4.2

編譯工具ndk

static int write_file(void)
{
	int fd = 0;
	int ret = 0;
	char str[32];
	FILE *fp = NULL;

	//C庫函式新建、寫
	LOGI("fuck1.txt\n");
	fp = fopen("/storage/sdcard0/Download/fuck1.txt", "a");
	ERROR(fp == NULL, err1, "fuck1.txt create file");

	fprintf(fp, "%s\n", "fuck always!\n");

	fclose(fp);

	//linux系統函式open新建、寫
#if 1
	LOGI("fuck2.txt\n");
	fd = open("/storage/sdcard0/Download/fuck2.txt", O_CREAT | O_WRONLY, 0644);
	ERROR(fd < 0, err1, "fuck2.txt open file");

	strcpy(str, "hello world!\n");

	ret = write(fd, str, strlen(str));
	LOGI("2 write bytes =%d\n", ret);

	close(fd);
#endif

	//linux系統函式creat/open 新建、寫
	LOGI("fuck3.txt\n");
	fd = creat("/storage/sdcard0/Download/fuck3.txt", 0644);
	ERROR(fd < 0, err1, "fuck3.txt creat file");

	fd = open("/storage/sdcard0/Download/fuck3.txt", O_WRONLY);
	ERROR(fd < 0, err1, "fuck3.txt open file");

	strcpy(str, "fuck world!\n");

	ret = write(fd, str, strlen(str));
	LOGI("3 write bytes =%d\n", ret);

	close(fd);


	return 0;

err1:
	return -1;
}

在上面這個應用中,linux系統函式open的兩個方法都可以成功使用:
<span style="white-space:pre">	</span>int open(const char *pathname, int flags);
       <span style="white-space:pre">	</span>int open(const char *pathname, int flags, mode_t mode);

其中兩個引數的open呼叫需要和creat函式結合使用。

但是在JNI中操作驅動裝置檔案時,則只能使用兩個引數的open來開啟,不能使用三個引數的open來開啟!!!

因為我直接把ubuntu的程式(可以開啟)移植到JNI中,一直open(三個引數的)失敗,後來我改成了兩個引數的open就可以開啟。

這個問題先放著,後面再細究其原因!

JNI程式:

int V4l2::v4l2_open(struct video_information *vd_info)
{

	ERROR(NULL == vd_device, err1, "video device name NULL!");
	LOGI("video name = %s\n", vd_device);

	vd_info->fd = open(vd_device, O_RDWR);
    if(vd_info->fd < 0)
    {
        LOGE("open: failed!");
        return -1;
    }
    return 0;

err1:
	return -1;
}