C++: open file for writing in the LocalStorage

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
Hi guys, could you tell me how to open file for writing in the phone app LocalStorage for the non-unlocked handset (regular app for store)?
Code below doesn't work :(
Code:
FILE *tmp;
auto tmpPath = Windows::Storage::ApplicationData::Current->LocalFolder->Path + "\\tmp.txt";
auto tmpErr = _wfopen_s(&tmp, tmpPath->Data(), L"w");
Any suggestions?
 

wcomhelp

Senior Member
May 1, 2012
107
16
0
Calgary
Try looking though msdn articles. I found it somewhere in there. But I have forgotten it now.

Sent from Board Express on my Nokia Lumia 1020. Best phone ever!!
Note to noobs: DON'T PM ME WITH QUESTIONS. POST IN THE FORUMS. THAT'S WHAT THEY ARE HERE FOR!
 

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
@wcomhelp, please keep your rtfm advices for yourself, OK? I'm not a noob and of course I've searched msdn, google, codeplex, github etc. and so on before posting here. If you don't know how, much better be silent (like others who read this post but have no idea what I'm talking about)

I've tried a few possible methods including ugly "MS-way" with task & lambda syntax (see below) but nothing worked as it should be (code below works if no file exist and fails if file already exist - CreationCollisionOption::ReplaceExisting options is not worked/not implemented/buggy/billgates_knows_only ).
Code:
        auto folder = Windows::Storage::ApplicationData::Current->LocalFolder;
	Concurrency::task<Windows::Storage::StorageFile^> createFileOp(
		folder->CreateFileAsync(CONFIG_FILE_NAME, Windows::Storage::CreationCollisionOption::ReplaceExisting));

		createFileOp.then([=](Windows::Storage::StorageFile^ file)
			{
				return file->OpenAsync(Windows::Storage::FileAccessMode::ReadWrite);
			})
			.then([=](Windows::Storage::Streams::IRandomAccessStream^ stream)
			{
				auto outputStream = stream->GetOutputStreamAt(0);
				auto dataWriter = ref new Windows::Storage::Streams::DataWriter(outputStream);

                                // data save code skipped

				return dataWriter->StoreAsync();
			})
			.wait();
BTW, I've used workaround, to save ported C++ app data to the LocalSettings instead of text file (as it was in original code).
 
Last edited:

GoodDayToDie

Inactive Recognized Developer
Jan 20, 2011
6,066
2,930
0
Seattle
"Doesn't work" doesn't give us a lot to go on, troubleshooting-wise. Can you tell us what error you get?
Only thing I see in the code that looks a little weird is that the
Code:
"\\tmp.txt"
part isn't explicitly a wide-character string, but I'd expect string concatenation to take care of that.
Also, out of curiosity, why libc functions instead of Win32? Obviously, the code you're writing here isn't intended for much portability...
 

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
@GoodDayToDie, there is no error code at all - standard POSIX functions returns NULL FILE, the ::GetLastError() also return 0.
I'm porting old C-style app to WinRT platform and don't care about portability (but the first post code - just a simplified example, nothing more).
POSIX (libc) functions works pretty well for reading only but not for writing - that's the problem...
As I said before, I resolved my issue by workaround but still curious why the POSIX calls fails for file writing in the app storage.
 

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
buuuuuuuuuuuuuuuuh

No need for lambdas
https://paoloseverini.wordpress.com/2014/04/22/async-await-in-c/

You may also want to rethink your strategy

You can't create files at arbitrary locations, so your method is kinda redundant. All the locations you are allowed to create and read files to/from are available through KnowFolders and ApplicationData classes. These return StorageFolders which in turn can create files with CreateFileAsync (used for both creating and opening existing files) and get files with GetFilesAsync ( I recommend against this one though) and similar methods.
 

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
@mcosmin222, could you please re-read my posts one more time? I'm not trying to create files at "arbitrary locations"; I wanna create/write simple text file at the app's local storage (which one should be available for reading/writing). And the problem not in the lambdas or task usage (yes, it looks ugly but it works as it supposed to be).
Could you provide a working example instead of words? And I'll be glad to say you "thanks a lot"; can't say now...
 
Last edited:

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
@mcosmin222, could you please re-read my posts one more time? I'm not trying to create files at "arbitrary locations"; I wanna create/write simple text file at the app's local storage (which one should be available for reading/writing). And the main problem not in the task (async execution).
Could you provide a working example instead of words? And I'll be glad to say you "thanks a lot"; can't say now...
Sure, just gimmie a few hours till I can get near a compiler that is capable of doing that :p
 

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
Of course, no rush at all, take your time. It's not a showstopper for me now (actually, my workaround with AppSettings is more preferable way - at least for universal app and roaming settings) but the issue still has an "academic interest" and maybe will be useful in the next projects for porting old C/C++ code to WinRT.
 

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
Of course, no rush at all, take your time. It's not a showstopper for me now (actually, my workaround with AppSettings is more preferable way - at least for universal app and roaming settings) but the issue still has an "academic interest" and maybe will be useful in the next projects for porting old C/C++ code to WinRT.
hi

in vs 2015

#include <pplawait.h>

Something of the like should work

Code:
WriteSomeFile() __resumable
{
	auto local = ApplicationData::Current->LocalFolder;
	auto file = __await local->CreateFileAsync("some file", CreationCollisionOption::eek:penIfExists);

	__await FileIO::WriteTextAsync(file, "this is some text");
}
However, as of right now, in VS 2015 RC, you have a host of limitations when dealing with this, but I do not believe this will be of any issue to you.
Code:
    Cannot use Windows Runtime (WinRT) types in the signature of resumable function and resumable function cannot be a member function in a WinRT class. (This is fixed, but didn't make it in time for RC release)
    We may give a wrong diagnostic if return statement appears in resumable function prior to seeing an await expression or yield statement. (Workaround: restructure your code so that the first return happens after yield or await)
    Compiling code with resumable functions may result in compilation errors or bad codegen if compiled with /ZI flag (Edit and Continue debugging)
    Parameters of a resumable function may not be visible while debugging
Please see this link for additional details

http://blogs.msdn.com/b/vcblog/archive/2015/04/29/more-about-resumable-functions-in-c.aspx

you should also note that this works with native, standard C++ types.
 
  • Like
Reactions: sensboston

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
@mcosmin222, looks like unbuffered writing works (i.e. without streams) fine but it still not an answer for my initial question :)
I'm curious why the standard POSIX libc writing operations are not working on the app's local storage (but reading from files works fine). Actually, it's all about porting old C/C++ code for WinRT; of course for the new app it's not a problem but re-writing old code to FileIO should be a huge pain in the ass. What I did: I've "mechanically" changed all libc formatted outputs from file to string, and use LocalSettings class (actually it's XML file) to store that string (I'm planning also change LocalSettings to RoamingSettings, to provide settings consistency between WP & desktop app).

P.S. <pplawait.h> is not available in my VS 2015 (release pro version) so I've tested by using lambda pattern.
 
Last edited:

GoodDayToDie

Inactive Recognized Developer
Jan 20, 2011
6,066
2,930
0
Seattle
OK, first things first, LIBC != POSIX! The POSIX way to do this would be to call the open() function and get back an int as an "fd" (file descriptor), which is of course not implemented on Windows Phone because Windows Phone is not a POSIX platform (you might find the Windows compatibility functions _open() and _wopen(), but I doubt it). You are attempting to use the standard C library functions, which are portable but implement kind of a lowest common denominator of functionality and are generally slightly slower than native APIs because they go through a portability wrapper.

Second, sorry to be all RTFM on you but you should really Read The Manual (or manpage, or, since this is Windows, the MSDN page)! Libc APIs set errno (include errno.h) and use different error values than Windows system error codes (or HRESULT codes, or NTSTATUS codes, or...). Error reporting in C is a mess. If you were calling CreateFile(), you would check GetLastError(), but since you're calling _wfopen(), you check errno (not a function).
 
Last edited:

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
@GoodDayToDie, _wfopen_s returns 0 (i.e. "no error") but tmp pointer receives also 0 (NULL) :) Could you explain why libc file functions are working for reading (at the app installation & local data folders of course) but not for writing? Any logical ("msdn based") explanation? ;) Or you just... don't know, heh? ;)
 

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
@GoodDayToDie, _wfopen_s returns 0 (i.e. "no error") but tmp pointer receives also 0 (NULL) :) Could you explain why libc file functions are working for reading (at the app installation & local data folders of course) but not for writing? Any logical ("msdn based") explanation? ;) Or you just... don't know, heh? ;)
LIBC functions will most likely work just in debug mode. The moment you try to publish the app it will fail. You can do lots of crazy stuff on your developer device with basic C functions, but if you try publishing, it won't pass the marketplace verification.

Most C APIs are simply not supported, since they do not comply with the sandbox environment of the Windows Runtime.

The code I gave you is tested with VS 2015 RC. You should be able to include <pplawait.h> just fine, if you are targeting toolchains newer than November 2013.
 

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
The moment you try to publish the app it will fail. You can do lots of crazy stuff on your developer device with basic C functions, but if you try publishing, it won't pass the marketplace verification.
Hmm... Are you sure or it's just your assumption? My app is still under development but (just for test!) I've made store app package for WP and it passed local store verification :p I also uploaded package to the store (via browser) and it also passed. I don't have time to create all tiles and fill all fields to complete beta-submission (actually, I don't know how to mark app as beta in the new dashboard) but for me it looks like app don't have any problem and will pass store certification easily. And you may be sure - it uses A LOT of libc calls 'cause originally it was written for Linux (or kind of UX system) :)
 
Last edited:

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
Hmm... Are you sure or it's just your assumption? My app is still under development but (just for test!) I've made store app package for WP and it passed local store verification :p I also uploaded package to the store (via browser) and it also passed. I don't have time to create all tiles and fill all fields to complete beta-submission (actually, I don't know how to mark app as beta in the new dashboard) but for me it looks like app don't have any problem and will pass store certification easily. And you may be sure - it uses A LOT of libc calls 'cause originally it was written for Linux (or kind of UX system) :)
Once usage reports get up to microsoft, you will be given a notice to fix the offending API (happened to be once). You are much better off using the platform specific tools: not only they are much faster, they are also much safer and you won't have problems later on.

You might get away with reading stuff (since reading is not that harmful), but you should be using the winRT APIs each time they are available.

Simply uploading your app to the marketplace just reruns the local tests in their cloud servers: once you submit the actual app (not beta, not tests) for consumers, it will be much more aggressively checked. This is because the store allows specific scenarios for distributing apps in close circles that may break the usual validation rules.
 
Last edited:

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
@mcosmin222, one more time: is it your assumptions or personal experience? I don't know how many apps you have in store (I do have a lot) but I never heard that you said. I've used C++ libraries with WP hacks in some of published apps but never had any problem with "aggressive checks". What I know: if you are using some "prohibited" calls, your app will not pass uploading to the store (uploading, not a certification).

P.S. I'll send you personally a link when I publish release :p Hope, you'll like it ;)
 
Last edited:

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
@mcosmin222, one more time: is it your assumptions or personal experience? I don't know how many apps you have in store (I do have a lot) but I never heard that you said. I've used C++ libraries with WP hacks in some of published apps but never had any problem with "aggressive checks". What I know: if you are using some "prohibited" calls, your app will not pass uploading to the store (uploading, not a certification).

P.S. I'll send you personally a link when I publish release :p Hope, you'll like it ;)

By "hacking" you mean recompiling the code to fit the windows phone toolchain? if so, then you shouldn't have to worry about too many things.

but even so, calling stuff like fopen in locations other than local storage will get your app banned. Even if it makes past the first publication, you can get noticed weeks later or even months (yes, it did happen to me personally).

In most cases, calling C APIs that can potentially break the sandbox (like opening a file in doc library with fopen) will always fail the marketplace verification, eventually. If it hasn't happened to you yet, then you may have not been using such APIs.
 

sensboston

Recognized Developer
Nov 18, 2009
2,142
797
193
Boston, MA
No, my C++ code is not accessing other than approved locations but the app has a lot of libс (and of course other C/C++ libs) calls; I'm 99.9% sure it's legitimate and will be not a source of any problem. Otherwise what is the advantages of having C++ compiler?!
As far as I know, just some of API's are prohibited but you will notice it right after local store compatibility test run...

As for "hacks" I mean usage of undocumented ShellChromeAPI calls (including loading hack).

P.S. I've found why <pplawait.h> header is missing. Initially I've created solution with the 12.0 toolset but now I can't (or don't know how to) change it to 14. However creating the new empty universal solution in VS 2015 also gives me toolset 12 by default. What is the toolset 14 for? Windows 10?
 

mcosmin222

Senior Member
May 1, 2012
1,130
287
0
No, my C++ code is not accessing other than approved locations but the app has a lot of libс (and of course other C/C++ libs) calls; I'm 99.9% sure it's legitimate and will be not a source of any problem. Otherwise what is the advantages of having C++ compiler?!
As far as I know, just some of API's are prohibited but you will notice it right after local store compatibility test run...

As for "hacks" I mean usage of undocumented ShellChromeAPI calls (including loading hack).

P.S. I've found why <pplawait.h> header is missing. Initially I've created solution with the 12.0 toolset but now I can't (or don't know how to) change it to 14. However creating the new empty universal solution in VS 2015 also gives me toolset 12 by default. What is the toolset 14 for? Windows 10?
The advantage of C++ is the obvious versatility: the standard C++ APIs will work fine for you as long as you stay inside the sandbox (this means you can't access files even in locations that are outside of sandbox but you have permission to them, such as music library). You can use most classic C/C++ libraries without issues as long as you do the interface with the runtime broker yourself. That means using windows runtime APIs instead of classic C APIs when dealing with stuff such as file access, for example. This is a pretty extensive topic and It is rather difficult to explain it all with 100% accuracy, especially when there is lots of docs running around.

You also get deterministic memory management, which is huge in specific scenarios.

Long story short

You will be fine with standard C/C++ when using

any in-memory functions supported by the compiler (you can manipulate data types, string, mutex, etc).
File IO in isolated storage only (applicationData folder)

Threads (although you are better off using threadpool or the like, it is much easier and cleaner). You can also use futures, and std::this_thread.

You will have to use winRT replacement

File system access in any other location than application data (you must use the windows::storage APIs)
sockets, internet access and the like.
any hardware related thing: music&video playerback must be interfaced through winRT (although the underlying decoders can be classic C/C++), messing around with the device sensors.
Retrieving system properties (internet connection state etc)
cross process communications
communicating with other apps


There are also win32 equivalents

mutex, threading, fileIO (isolated storage only)
Media playback with custom rendering pipeline.


Basically, winRT functions as an abstraction layer between the hardware and your code. You can use classic C++ up to the point where you need to interact with the system in any way. At that point, system interaction must be done with winRT. This way, microsoft ensures a higher degree of stability and security for devices.


check this link out for more information on the toolchains. You should be able to use this in VS 2013 as well with windows 8 (this is a compiler feature, has nothing to do with supported platform)

https://paoloseverini.wordpress.com/2014/04/22/async-await-in-c/
 
Our Apps
Get our official app!
The best way to access XDA on your phone
Nav Gestures
Add swipe gestures to any Android
One Handed Mode
Eases uses one hand with your phone