Skip to content

Instantly share code, notes, and snippets.

@lattice0
Created February 9, 2021 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lattice0/c83234be17b0864d4450dd2aeb4258a2 to your computer and use it in GitHub Desktop.
Save lattice0/c83234be17b0864d4450dd2aeb4258a2 to your computer and use it in GitHub Desktop.
c++ file open/write test android
ALOGV(TAG, "#####################################################################");
std::fstream f;
ALOGV(TAG, "original filePath: %s", filePath.c_str());
std::string filePath2 = "/storage/emulated/0/Android/data/com.stompai.flutter_app/files/something_3.txt";//filePath + "22w";
ALOGV(TAG, "gonna open filePath2: %s", filePath2.c_str());
f.open(filePath2, std::ios_base::binary | std::ios_base::in | std::ios_base::out);
if (f.is_open()) {
ALOGV(TAG, "is open");
} else {
ALOGV(TAG, "is closed");
}
//Write some data to vector
std::vector<char> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
//Go to beggining of the file to write
f.seekg(0, std::ios::beg);
f.seekp(0, std::ios::beg);
//Write the vector to file
f.write(v.data(), v.size());
f.flush();
//Lets read so we see that things were written to the file
ALOGV(TAG, "seeking g and p to beggining");
//Don't know why I've put clear, but won't work without it too
//f.clear();
f.seekg(0, std::ios::beg);
f.seekp(0, std::ios::beg);
auto v2 = std::vector<char>(v.size());
//Read things back to file
f.read(v2.data(), v2.size());
if (f) {
ALOGV(TAG, "did read everything");
} else {
ALOGV(TAG, "did read only : %d", f.gcount());
}
auto* b1 = v2.data();
for (int i=0; i<v2.size(); i++) {
ALOGV(TAG, "b1[%d] = %d", i, b1[i]);
}
f.close();
//Lets open again to see if modifications were recorded permanently
ALOGV(TAG, "gonna open filePath2: %s", filePath2.c_str());
f.open(filePath2, std::ios_base::binary | std::ios_base::in | std::ios_base::out);
if (f.is_open()) {
ALOGV(TAG, "is open");
} else {
ALOGV(TAG, "is closed");
}
ALOGV(TAG, "seeking g and p to beggining");
f.clear();
f.seekg(0, std::ios::beg);
f.seekp(0, std::ios::beg);
std::vector<char> v3(v.size());
f.read(v3.data(), v3.size());
if (f) {
ALOGV(TAG, "did read everything");
} else {
ALOGV(TAG, "did read only : %d", f.gcount());
}
auto* b3 = v3.data();
for (int i=0; i<v3.size(); i++) {
ALOGV(TAG, "b3[%d] = %d", i, b3[i]);
}
f.close();
ALOGV(TAG, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment