Autostart application in Linux, output fail - c

friends. I am using Debian Linux (Raspberry Pi), I want to autostart a program after linux startup.
It's a C program, it can printf on Terminal and fprintf on a text file, I have compiled it and got exe file(file name is test) Path is /home/username/try/test ,the program can run successfully, printf and fprintf can work. After I got exe file, I run command
sudo chmod +x /home/usernane/try/test
Then I create a new folder "autostart" in /home/username/.config Then I run command
cd /home/username/.config/autostart
sudo nano test.desktop
I continue to write desktop file:
[Desktop Entry]
Name=test
exec=lxterminal -e "/home/username/try/test"
Type=Application
After this, I reboot. the program can autostart, but when the program start to fprintf, the program quit. I delete fprintf in code, redo everything, Program can run successful and can printf results.
so problem is fprintf(I want to output results to a txt file)! I tried many ways and can't solved. I need your suggestions, thanks!
I did fprintf as the following: (I run the program normally (Not Autostart), it can work.If autostart, program will quit)
FILE *fp;
char results[50]
/* check if file could be opened */
if((fp=fopen("xy.txt", "w")) == NULL) { // or use "a" instead of "w" to create the file if it doesn't exist
printf("Cannot open file.\n");
exit(1);
}
/* put your results into results[] */
....
/* afterwards writing to file */
fprintf(fp, "%s", results);
fclose(fp);

Have you tried to do it like this?:
FILE *fp;
char results[50]
/* check if file could be opened */
if((fp=fopen("test.txt", "w")) == NULL) { // or use "a" instead of "w" to create the file if it doesn't exist
printf("Cannot open file.\n");
exit(1);
}
/* put your results into results[] */
....
/* afterwards writing to file */
fprintf(fp, "%s", results);
fclose(fp);

Related

how to use fprintf in terminal (Mac OS)

I'm using esc ANSI code, ao I need to run my program via terminal. when I'm trying to use fprintf and executing the program from the console, nothing is saved in the text file. Running the program from Xcode directly, it does save the text in the file.
int main()
{
int write;
FILE *file;
file = fopen("frucht.txt", "w+");
gotoxy(4, 10);
scanf("%d", &write);
fprintf(file,"%d", write);
fclose(file);
return(0);
}

canĀ“t open txt file

#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^\n]", c);
printf("Data from the file:\n%s", c);
fclose(fptr);
return 0;
}
Output is Error! opening file
I have program and txt file in same dir.
How can I direct access to that file?
To diagnose, use the system command to issue a ls or dir depending on your platform. That will tell you where you are running from. Odds are it is a different location than the files you are trying to open.
As suggested in the comment, try replacing printf with perror
if ((fptr = fopen("program.txt", "r")) == NULL)
{
perror("Error");
// Program exits if file pointer returns NULL.
exit(1); // Exiting with a non-zero status.
}
perror prototype is
void perror(const char *str)
where str is the C string containing a custom message to be printed before the error message itself.
However some causes of the of the file not being read are
File is not present in the current working directory. If this is the case, rectifying the path should fix the issue.
The program might not have the permissions to read from the file usually because of a setting related to discretionary access control. Perhaps do a chmod with file?
I made a quick run of your program on TURBOC++ by Borland and it executed without complaining any sort of Warning or Error
As mentioned in the earlier posted answers, you should replace printf by perror
CURRENT REPLACE BY
printf("Error! opening file"); perror("Error! Opening File.");
As in your case of file not found printf("Error! opening file"); will result in :
Error! Opening file.
However in case of perror("Error! Opening File."); if the file program.txt does not exist, something similar to this may be expected as program output
The following error occurred: No such file or directory
The difference is obvious from above explanations.
Regarding your program, I am making an assumption that either your path to the file is wrong or there is some problem with your compiler.
Try to open your file in w+ mode also to ensure that the file exist.

c code popen error "can not allocate memory" only when running in virtual machine

I wrote a program using c, which I use popen to open a pipe and execute a command line.
This program works fine in host, but when I run the program in vbox, ubuntu12.04, error:can not allocate memory displayed.
My code is:
FILE *fp;
char path[100];
/* Open the command for reading. */
fp = popen(pdpcall, "r");
if (fp == NULL) {
printf("Error opening pipe pdpcall: %s\n",strerror(errno));
pclose(fp);
exit(0);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
if(strncmp(decision,path,strlen(decision))==0)
{
pclose(fp);
return 1;
}
I also try a test program only have popen in VM, it works fine. But can not work within my program.
I guess the reason is that in my program, I use a lot of malloc, and might not free. The memory in Vbox is smaller than host, so there are memories errors.
But I change the vbox memory from 512m to 2G, it still the same errors.
Is there any other problems within VM. How to solve this problems.

storing logs/error message on C programming

When an error occurs, I would like my C code to store the error before exiting the program. Is it advised to store the stderr to a file (e.g., /home/logs.txt) or would it be advised to use a different method to keep the logs/error report (considering the programming environment is Linux). E.g., for the code below, how I could apply the method to store the logs/error message on /home/log.txt or /home/log
FILE *fp1;
fp1 = fopen("/sys/class/gpio/export","w");
if(fp1 == NULL){
fprintf(stderr, "errno:%s - opening GPIO136 failed - line 739\n ", strerror(errno));
close(fp1);
exit(1);
}
Thank you.
If stderr is always used to print out all your error message, so, you can redirect output to a specific file.
$ program 2>~/logs.txt
For a better logging tool, you can use:
syslog standard function.
log4c library.
If you want to store the error, stderr is probably not a good choice because you'll need to pipe stderr to a file every time you run the program.
If you want to write to /home/log.txt, open a FILE pointer to it and write with fprintf the same way you tried to open /sys/class/gpio/export and write to that instead of stderr. Also be sure to open the log file with append mode.
FILE *fp1;
fp1 = fopen("/sys/class/gpio/export","w");
if(fp1 == NULL){
FILE *fpErr = fopen("/home/log.txt", "a");
if(fpErr != NULL)
fprintf(fpErr, "errno:%s - opening GPIO136 failed - line 739\n ", strerror(errno));
close(fpErr);
close(fp1);
exit(1);
}

Help with opening a file in C on Xcode

I'm trying to open a simple .rtf file called test in C. I'm using Xcode. My code is:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, const char * argv[]) {
FILE *filePtr;
filePtr = fopen("test.rtf", "r");
if (filePtr == NULL) {
fprintf(stderr, "Can't open \"test\"\n");
exit(EXIT_FAILURE);
}
else {
printf("File open successful\n");
int x;
/* read one character at a time until EOF is reached */
while ((x = fgetc(filePtr)) != EOF) {
printf("%c", x);
}
}
fclose(filePtr);
return 0;
}
I have the test.rtf file in the same directory as my Xcode.proj directory. My output is "File open successful", however I do not get anything read from the file. Am I doing this right? Thanks.
There's nothing wrong with that code at all. I tested it (albeit not in Xcode) with a file and the transcript was:
pax> echo hello >test.rtf
pax> ./qq.exe
File open successful
hello
So the obvious think to ask is what happens when you examine test.rtf? Does it actually have any content? Because, when I do:
pax> rm test.rtf ; touch test.rtf
pax> ./qq.exe
File open successful
I get the same behaviour you observe.
Also try renaming it to test2.rtf temporarily and make sure you get the error. It's possible it may be opening a different copy of the file than what you think (this often happens in Visual C since the directory the program runs in is not always what developers think at first).
It looks right.
As for the lack of output, two possibilities:
Are you sure the file has some content? Maybe ls -l test.rtf or dir test.rft
Possibly it has some control characters which cause the terminal to which it is written to suppress output.
Try moving test.rtf to your build directory. If your project is named MyProject, move it to MyProject/build/Debug/.
I can think of two things that could cause this problem. Either there is an error when calling fgetc, or you are getting output that you don't recognize.
fgetc() will return EOF when the end of the file is reached, or an error occurs. To determine if it's an error, just after your while loop try:
if (ferror(filePtr) != 0) printf("error: %d.\n", errno);
A .rtf file is not a plain text file. It likely contains a bunch of formatting information. You are expecting to see "Hello . . . ". but what you may actually see is something like:
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf250
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040
\f0\fs24 \cf0 Hello . . .
And you are just assuming that is GDB output, not your program's output.
Based upon your recent comments, I think you have an empty file test.rtf in the directory your program is run in, and your real test.rtf file is in some other directory. Maybe your fopen() call at some point was fopen("test.rtf", "w"); instead of fopen("test.rtf", "r");, and you later modified it.
To see the directory your program is running in, add the following to your program after the FILE *filePtr; line:
char pwd[512];
if (getcwd(pwd, sizeof pwd) != -1)
printf("In directory %s\n", pwd);
else
fprintf(stderr, "Need bigger buffer, change '512' above\n");
Then, you can open a terminal, do cd <directory>, and test for yourself if the file you want is the file your program is opening.
You probably want this file to be plain text, not rich text. Rich text has a lot of formatting encoded into the file.

Resources