Операции файла в Android NDK

Я использую NDK Android для подавания заявки, прежде всего, в C по причинам производительности, но кажется, что операции файла, такие как fopen не работают правильно в Android. Каждый раз, когда я пытаюсь использовать эти функции, сбои приложения.

Как я создаю/пишу в файл с NDK Android?

63
задан Janusz 18 June 2010 в 11:08
поделиться

1 ответ

Файл ввода-вывода прекрасно работает на Android, используя JNI. Возможно, вы пытаетесь открыть файл с плохим путем и не проверяете код возврата? Я модифицировал пример hello-jni, чтобы показать, что действительно можно открыть файл и написать в него. Надеюсь, это поможет.

/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <string.h>
#include <jni.h>
#include <stdio.h>

/* This is a trivial JNI example where we use a native method
 * to return a new VM String. See the corresponding Java source
 * file located at:
 *
 *   apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java
 */
jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                              jobject thiz )
{
    FILE* file = fopen("/sdcard/hello.txt","w+");

    if (file != NULL)
    {
        fputs("HELLO WORLD!\n", file);
        fflush(file);
        fclose(file);
    }

    return (*env)->NewStringUTF(env, "Hello from JNI (with file io)!");
}

Вот результат после запуска на моем телефоне (с SD-картой):

$ adb -d shell cat /sdcard/hello.txt
HELLO WORLD!
62
ответ дан 24 November 2019 в 16:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: