Simultaneously write and read a file from NDK in android

那年仲夏 提交于 2019-12-12 04:22:29

问题


I am writing into a file using android-ndk . So writing in file is taking place using native c code.

It contains some kind of readings that i am putting in using ndk. On click of a button the writing into a file start. And simultaneously i want to read contents of file and use them into another thread for showing up the values as writing operation might continue for 15 sec and user will have to wait for that much time to see the result so i want to show result one by one as soon as i get it into that file.

Is it feasible ,if yes can show me the way how to go about that?

Well i started with it and right nw its how i am doing it ,,

Thread thr1 = new Thread(r1);
Thread thr2 = new Thread(r2);
thr1.start();
thr2.start();



r1 = new Runnable() {
          public void run() {
            File sdcard= Environment.getExternalStorageDirectory();
            nativeFunction(sdcard +"/readings.txt");
            //takingReading=false;
            readingFile = new File(sdcard +"/readings.txt");

            Log.i("length of file", ""+readingFile.length());
          }
        };




r2 = new Runnable() {
          public void run() {
            try {

                  Thread.sleep(3000);
                  File sdcard= Environment.getExternalStorageDirectory();

                readingFile = new File(sdcard +"/readings.txt");

                Log.i("length of file", ""+readingFile.length());


            } catch (InterruptedException iex) {}
          }
        };

nativeFunction opens

file= fopen(location,"w+");

This function keeps on writing things in file for around 2 minutes, but i need to continuously get the values entered bye native function so i started 2nd thread but when i check file.length() its always 0.

and when nativefunction write is complete then actual file size comes. So how to get around this problem?


回答1:


This should be possible using pthreads. So you need to spawn 2 threads, one doing the writing and other doing the reading. If you are doing it from the same file, you may run into race conditions, so be careful.

More more info on pthreads, kindly google. It's commonly used by the Linux world.



来源:https://stackoverflow.com/questions/12856215/simultaneously-write-and-read-a-file-from-ndk-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!