1.建管道,拷贝test.264文件,新建copy.264
fifo_write.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>
#include <android/log.h>
#include <jni.h>
#define FIFO_NAME "/sdcard/fifo/fifo1"
JNIEXPORT jint JNICALL Java_com_example_fifotest_FifoAndroid_write(JNIEnv * env, jclass obj)
{
FILE* file = NULL;
int fifo_fd;
if(access(FIFO_NAME, F_OK) == -1)
{
fifo_fd = mkfifo(FIFO_NAME, 0777);//直接在adb下创建(提示没有mkfifo命令)或者在linux创建fifo拷贝过来变成文件而非管道文件
if(fifo_fd < 0) //只有这种方法才能建立管道文件,可能是android的权限问题吧。
{
return 0;
}
}
fifo_fd = open(FIFO_NAME, O_WRONLY);
char* tempBuffer = NULL;
file = fopen("/sdcard/fifo/test.264","rb");
if(file == NULL)
{
return -1;
}
tempBuffer = (char*)malloc(1024);
if(tempBuffer == NULL)
{
return -1;
}
while(0==feof(file))
{
size_t n = fread(tempBuffer,1,1024,file);
size_t num =write(fifo_fd, tempBuffer, n);
while (num == -1)
{
num = write(fifo_fd, tempBuffer, n);
}
}
fclose(file);
free(tempBuffer);
return 0;
}
fifo_read.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <limits.h>
#include <android/log.h>
#include <jni.h>
#define FIFO_NAME "/sdcard/fifo/fifo1"
JNIEXPORT jint JNICALL Java_com_example_fifotest_FifoAndroid_read(JNIEnv * env, jclass obj)
{
FILE* file = NULL;
int fifo_fd;
if(access(FIFO_NAME, F_OK) == -1)
{
fifo_fd = mkfifo(FIFO_NAME, 0666);
if (fifo_fd < 0)
{
return 0;
}
}
fifo_fd = open(FIFO_NAME, O_RDONLY);
char* tempBuffer = NULL;
file = fopen("/sdcard/fifo/copy.264","w+");
if(file == NULL)
{
return -1;
}
tempBuffer = (char*)malloc(1024);
if(tempBuffer == NULL)
{
return -1;
}
size_t num;
while(num)
{
num = read(fifo_fd,tempBuffer,1024);
if (num > 0)
{
size_t n = fwrite(tempBuffer,1,1024,file);
}
}
fclose(file);
free(tempBuffer);
return 0;
}
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE :=FifoAndroid
LOCAL_SRC_FILES :=fifo_write.c fifo_read.c
LOCAL_LDLIBS := -llog -ljnigraphics -lz -landroid
include $(BUILD_SHARED_LIBRARY)
记得加sd卡权限。
本文介绍了如何在Android应用中利用C++创建管道,并通过管道进行文件拷贝的过程,包括创建管道、读取文件、写入管道及文件拷贝的实现细节,最终展示了一个简单的应用实例。
630

被折叠的 条评论
为什么被折叠?



