How to open files from a NaCl Dev Environment application? - c

I'm trying to get a simple command line application to run in the NaCl Development Environment. But I don't understand why it doesn't want to open files:
#include <stdio.h>
#include <ppapi_simple/ps_main.h>
int my_main (int argc, char ** argv) {
FILE * f = fopen ("out.txt","w");
if (f) {
fputs ("output to the file", f);
fclose(f);
} else {
puts("could not open file");
}
}
PPAPI_SIMPLE_REGISTER_MAIN(my_main)
Running:
bash.nmf-4.3$ gcc -I"$NACL_SDK_ROOT/include" test.c -lppapi_simple -lnacl_io -lppapi
bash.nmf-4.3$ ./a.out
could not open file
bash.nmf-4.3$
It's clearly possible for an application to open files in arbitrary locations within the dev environment - I'm using nano to edit the test code! But the naclports version of nano doesn't look like it's been changed in ways that are immediately connected to file manipulation..?
Lua is another app that appears to have only been modified very slightly. It falls somewhere in between, in that it can run test files but only if they're placed in /mnt/html5, and won't load them from the home folder. My test program shows no difference in behaviour if I change it to look in /mnt/html5 though.
NB. my goal here is to build a terminal application I can use within the dev environment alongside Lua and nano and so on, not a browser-based app - I assume that makes some difference to the file handling rules.

Programs run in the NaCl Dev Environment currently need to linked with -lcli_main (which in turn depends on -lnacl_spawn) for an entry point which understands how to communicate with the javascript "kernel" in naclprocess.js. They need this to know what current working directory they were run from, as well as to heard about mounted file systems.
Programs linked against just ppapi_simple can be run, but will not setup all the mount points the dev environment may expect.
There is a linker script in the dev env that simplifies linking a command line program -lmingn. For example the test program from the question can be compiled with:
gcc test.c -o test -lmingn
NOTE: This linker script had a recently resolved issue, a new version with the fix was published to the store on 5/5/2015.
In the near future, we have plans to simplify things further, by allowing main to be the entry point.
Thanks for pointing out the lua port lacks the new entry point!
I've filed an issue and will look into fixing it soon:
https://code.google.com/p/naclports/issues/detail?id=215

I found a solution to this, although I don't fully understand what it's doing. It turns out that the small changes made to nano are important, because they cause some other functions elsewhere in the NaCl libraries to get pulled in that correctly set up the environment for file handling.
If the above file is changed to:
#include <stdio.h>
int nacl_main (int argc, char ** argv) {
FILE * f = fopen ("out.txt","w");
if (f) {
fputs ("output to the file", f);
fclose(f);
} else {
puts("could not open file");
}
}
...and compiled with two more libraries:
gcc -I"$NACL_SDK_ROOT/include" test.c -lppapi_simple -lnacl_io -lppapi -lcli_main -lnacl_spawn
...then it will work as expected and write the file.
Instead of registering our own not-main function with PPAPI_SIMPLE_REGISTER_MAIN, pulling in cli_main causes it to do so with an internal function that sets some things up, presumably including what is needed for file writing to work, and expects to then be able to call nacl_main, which is left to the program to define with external visibility (several layers of fake-main stacking going on). This is why the changes to nano look so minimal.
nacl_spawn needs to be linked because cli_main uses it for ...something.

Related

connecting sqlite to C program

[SOLVED]
All I had to do was open the sqlite3.c file inside my "project tree" like this and include sqlite3.h in the header.
I'm trying to connect my C program (using Code Blocks) to a database. I've already downloaded all the key files from the sqlite website like amalgamation zip file that comes with shell.c, sqlite3.c, sqlite3.h, and sqlite3ext.h.
I found this this tutorial on how to use libraries on code blocks. It's pretty simple, but then I realized that none of the files that came with amalgamation zip were .lib or .a. I know sqlite uses libraries, but all the files I listed above are source code files that access those libraries by themselves.
How to compile sqlite -> On their web site they have some good info: Everything is contained within a single code file, so it is easy to drop into the source tree of a larger C or C++ program. They meant the sqlite3.c file. But what did they mean by "dropping into the source tree"?
On the same page, there is a section Compiling The Command-Line Interface. I kind of got it the main points... I also found a sqlite shell tutorial here, so I downloaded the shell and now I can create/modify DBs. Although I feel like I'm pretty close to getting it to work on my C program, I still can't implement any DB from the source files or shell into my code.
Any thoughts?
#include <stdio.h> // printf
#include <sqlite3.h> // SQLite header (from /usr/include)
int main()
{
sqlite3 *db; // database connection
int rc; // return code
char *errmsg; // pointer to an error string
/*
* open SQLite database file test.db
* use ":memory:" to use an in-memory database
*/
rc = sqlite3_open(":memory:", &db);
if (rc != SQLITE_OK) {
printf("ERROR opening SQLite DB in memory: %s\n", sqlite3_errmsg(db));
goto out;
}
printf("opened SQLite handle successfully.\n");
/* use the database... */
out:
/*
* close SQLite database
*/
sqlite3_close(db);
printf("database closed.\n");
}
Also, on the Command Line Shell For SQLite you can find a detailed explanation on how to transfer existing data (created from outside the C program since I still can't connect the DB to my C program) to a .txt file. This is good to know and all, but not exactly what I want. I could make it work using a lot of fread, fprintfetc...but that's not quite as good as having a actual DB implemented into your program. For instance, if later I wanted to make my program.c into a program.exe I could do it with the DB embedded inside the program.exe.
The amalgation expects that you put all files of the amalgation in you project folder, that you add #include "sqlite3.h" in your sources that want to access sqlite and that you make sqlite3.c a member of your project.
Assuming a gcc command line compiler, you should do:
gcc main.c sqlite3.c -lpthread -o foo
No need for a library here, and never try to include sqlite3.c.

multiple definition of main first defined here

I'm new to programming and currently I'm learning C programming. I'm writing codes on the code blocks and in it using GCC compiler. When I create a new project, (as you know it creates main.c file with it) and due to that I'm not able to compile another file in that project.
File 1:
#include<stdio.h>
int main()
{
int a,b,c,d;
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
d=a;
if(b>d)
d=b;
if(c>d)
d=c;
printf("\n The maximum of three numbers is %d",d);
}
File 2: main.c
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}
When I compile the first programme, it shows the following error:
multiple definition of 'main'
first defined here
I've searched every where I could and I'm not able to solve this. In one of the answers here on stack overflow, someone had suggested to write this in
(Project->Build options...->Linker settings (tab))
-Wl,--allow-multiple-definition
When I wrote it, there were no errors. But it wasn't able to run my File 1 and instead, it runs that main.c file. Even when I close the main.c file, it opens there again and runs main.c file which gives the output "Hello World!".
Initially when I was using code blocks there were no such errors. I don't know why this is happening and I've not much knowledge about compilers.
As noted in comments you can only have one main function.
So when you start a new project you need to replace the main.c file with the main.c file you want to use. Or you can edit the 'hello world' main.c program.
When you start a new project in code::blocks you can get a new directory with a simple program that prints 'Hello World'. This file is usually main.c. You need to edit this file or replace it. The reason that code::blocks puts this simple main.c program in the new project is so that you can compile it and test your system without having to write a new program.
Some computer languages allow you to use the same function name for different functions ( which are identified by their parameters and sometimes return types ). That's called overloading. C does not allow this. Functions in C must have unique names.
The main() function is a special one in C as it is used as the standard entry point for applications. That is, the main() function will be called first and your application should start and (typically) end in that function.
As a beginner I would suggest you avoid automated editor features that create and build projects for you. You will miss out on learning how things work doing that. Use an editor to start from empty files and learn how they all connect and how to use the compiler from the command line. The command line is something every beginner should start from, IMO.
It may be harder to learn, but it will give you a much better feel for what is going on.
I guess what you maybe trying to do is have multiple sandbox "gists" that you may wanna run all as their own main function. If that is the case, then just close your project and open the files directly. As long as they are not in a project, they will run fine.

How to call same file as different name for different method?

I was recently at a presentation where one of the speakers stated that he'd used a single CGI file, written in C, that is called by the webserver, but the webserver calls the file by using different names, the CGI file would run a different method.
How can I have a single C file execute different functions within when it is called by different names? Also how do I re-direct the calls for differently named files back to this single file?
Is this possible or was he just full of himself?
If you create the executable with different names but with the same code base, you can take a different branch of the code based the name of the executable used to invoke the program.
Simple example file:
#include <stdio.h>
#include <string.h>
int main1(int argc, char** argv)
{
printf("Came to main1.\n");
return 0;
}
int main2(int argc, char** argv)
{
printf("Came to main2.\n");
return 0;
}
int main(int argc, char** argv)
{
// If the program was invoked using main1, go to main1
if (strstr(argv[0], "main1") != NULL )
{
return main1(argc-1, argv+1);
}
// If the program was invoked using main2, go to main2
if (strstr(argv[0], "main2") != NULL )
{
return main2(argc-1, argv+1);
}
// Don't know what to do.
return -1;
}
Create two different executables from the file.
cc test-262.c -o main1
cc test-262.c -o main2
Then, invoke the program by using the two different executables:
./main1
Output:
Came to main1.
and...
./main2
Output:
Came to main2.
Unix filesystems support the concept of hard and soft links. To create them just type:
ln origfile newfile
to create a hard link, or:
ln -s origfile newfile
to create a soft link.
Soft links are just a special kind of file that contains the path of another file. Most operations in the link transparently result in operating on the target file.
Hard links are lower level. In effect, all files are a link from the pathname to the content. In Unix you can link more than one pathname to the same content. In effect, there's no "original" and "links", all are links. When you delete a file, you're just removing a link, and when the link count goes to zero, the content is removed.
Many unix utilities do this trick. Since the running shell includes the name used to invoque the executable, it's handled just like the 0'th argument of the command line.
When a CGI script is being called by a web server, it receives a considerable amount of information in its environment to let it know how it was called, including:
SCRIPT_NAME, the path to the script from the document root
SCRIPT_FILENAME, the filesystem path to the script (usually the same as argv[0])
REQUEST_URI, the path that was requested by the browser (usually similar to SCRIPT_NAME in the absence of URL rewriting)
QUERY_STRING and PATH_INFO, which contain URL parameters following the script's name
HTTP_*, which contain most of the HTTP headers that were passed in the request
Point is, the script gets a lot of information about how it was called. It could be using any of those to make its decision.
It's possible and actually pretty common.
The first element in the argv array passed to the main function is the "name" of the executable. This can be the full path, or it can be just the last component of the path, or -- if the executable is started with an exec* function call, it can be an arbitrary string. (And Posix allows it to be a null string, as well, but in practice that's pretty rare.)
So there is nothing stopping the executable from looking at argv[0] (having first checked to make sure that argc > 0) and parsing it.
The most typical way to introduce a different name for the executable is to insert a filesystem link with the alternate name (which could be either a hard or a soft-link, but for maintainability soft links are more useful.)
For CGIs, it is not even necessary to examine argv[0], since there are various useful environment variables, including (at least): SCRIPT_NAME.

program doesnt work if called from another folder

In Command Prompt, this works: whatever\folder> bezier.exe
but this doesn't: whatever> folder\bezier.exe
My bezier program loads some settings from a local file, so I believe the problem is that the program thinks its directory is whatever\ when it is actually whatever\folder\. I'm calling it from within a C program using CreateProcess(). If I am correct in guessing the problem, is there any way to ensure the program has the right directory for itself?
the main method of bezier.exe:
int main(int argc, char* argv[]) {
char buf[200];
FILE* f = fopen("out.txt","w");
GetCurrentDirectory(200,buf);
fprintf(f,buf);
fclose(f);
SDL_Surface* screen;
SDL_Event e;
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_FULLSCREEN|SDL_HWSURFACE);
if (screen == NULL)
exit(-1);
SDL_ShowCursor(SDL_DISABLE);
srand(time(NULL));
loadColors(COLOR_FILE);
fill(screen, backColor);
initialiseVars();
while (e.type != SDL_KEYDOWN)
{
//do stuff
}
SDL_Quit();
return 0;
}
Here's the crazy part. With "..> folder\bezier.exe" it doesn't write its path, but it does start a new window. That doesn't make any sense to me, because SDL_SetVideoMode is after writing the path.
You can use GetModuleHandle and GetModuleFileName to find out where your execuatble file is, then use that information to create a file specification for your local settings file.
GetModuleHandle with a NULL argument will give you the handle for the current executable. Then, passing that to GetModuleFileName will give you the fully qualified name of that executable. Just strip off the executable filename from the end and add your configuration file name.
However, that's been a bad idea for a long time now, since Windows provides per-application and per-user settings areas for this sort of stuff - you can generally get those locations with SHGetFolderLocation() and its brethren.
Use the first method only if this is for a personal project. If you plan to release your software to the wild, you should separate executable and configuration information as per Microsoft guidelines.
Regardless of that, it appears you now have the problem that you think the file is not being written to. You need to check that. When you open that file out.txt for write, it does so in the current directory. If you're running in the parent directory (with folder\bezier.exe), it will create it in the parent directory and looking for it in the folder directory is a waste of time.
If you are looking in the directory where you're running the program from, and it's still not being created, there are possible reasons for this. For a start, you should check (ie, capture and output) the return codes from all those f* functions, fopen, fprintf and fclose.

Opening a file in Mac OS X

I am trying to open a text file with C++ in Mac OS X but I always get a Bus error.
I do not care where to put the file. I just need to read it. Am I writing its address wrong? or that Bus Error has another reason?
FILE *dic;
dic = fopen("DICT","rb");
dic = fopen("./DICT","rb");
dic = fopen("~/DICT","rb");
dic = fopen("~//DICT","rb");
With a little bit of clarification I see the problem in your C code (not C++!) is that fopen() returns NULL. You can check what the problem really is by reporting the detailed error:
if( (dic = fopen("DICT", "rb") == NULL ) {
fprintf(stderr, "%s\n", perror("ERROR:"));
exit(1);
}
If fopen() fails to find the file on the user's desktop and you wish your code to work on multiple platforms then you might define a function to get the user's desktop directory for using with fopen(). Something like
char* user_desktop(char* buf, size_t len)
{
const char* const DESKTOP_DIR =
#ifdef PC
"C:\\Documents and Settings\\Pooya\\Desktop\\"
#elif defined(OSX)
"/Users/Pooya/Desktop/"
#elif defined(LINUX)
"/home/users/pooya/Desktop/"
// fail to compile if no OS specified ...
#endif
return strncpy(buf, DESKTOP_DIR, len);
}
You probably want to look into a more robust way of getting the path of the desktop for each operating system. Most operating systems have an API for this, so do your research. There are also more robust ways of splitting behaviour for various platforms, you can look into that or open a different question about that. I just wanted to express my idea, of having a function which will return you the appropriate desktop path no matter on which platform you compile your code.
This code is correct! Pay attention to the directory where the executable is located. For sure the directory of the execution is not the same as you are expecting (I suppose, the directory of the .c files, right?).
I believe you are executing the app from the IDE. This is commom in Xcode, it mounts the exec`s in another location than that where the project files are located, and this such location that is considered when you execute the program, whether you execute it from the IDE or not!
Simply move the file you want to read to the location of the application and it will work properly.

Resources