Trying my hand at writing some C scripts, I have some code that should save a string to a file before rebooting the system. Both work separately but trying to write to file immediately before rebooting fails...
int writeToConfFile(char* filename, char* newConf) {
FILE *fp;
int status;
fp = fopen(filename, "w");
fprintf(fp,"%s",&newConf[0]);
status = fclose(fp);
return status;
}
int main(int argc, char **argv){
char extraString[1024];
strcpy(extraString,"0");
writeToConfFile("/etc/filename", extraString);
reboot(RB_AUTOBOOT);
}
adding sleep(10) between writeToConfFile and reboot does the trick, but I would like to do it in a neater way.
edit: the os is a heavily customized legacy debian.
edit2: tried changing writeToConfFile to end like this:
fp = fopen(filename, "w");
fprintf(fp,"%s",&newConf[0]);
fflush(fp);
status = fclose(fp);
return status;
but it didn't work either
As mathieu and jamieguinan suggested, calling sync() before reboot makes sure changes are written to disk
so the code ends thus:
writeToConfFile("/etc/filename", extraString);
sync();
reboot(RB_AUTOBOOT);
Related
Below is a part of my code which is having issues with file handling. The file opens fine with fopen but when I try to read or just close the file my program exits without an error. I tried to run this code independently and it works fine. Would really appreciate if someone could help me out which pointing out what I am doing wrong.
int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID)
{
char intName [10]; // Interface name from file
int intVlan; // Interface VLAN from file
printf("In ctrlSend\n");
FILE * pFile; // File pointer
pFile = fopen ("vlan.conf","r");
while(!feof(pFile))
{
fscanf(pFile,"%s %d",intName,&intVlan)
printf("In ctrlSend while loop");
}
fclose (pFile);
return 0;
}
UPDATE1: Updated above code
UPDATE2: Alternate code below which has same issue.
int ctrlSend(char *etherPort, uint8_t *inPayload, int payloadLen, int vlanID)
{
printf("In ctrlSend\n");
char intName [10]; // Interface name from file
int intVlan; // Interface VLAN from file
FILE * pFile; // File pointer
pFile = fopen ("vlan.conf","r");
while (fscanf (pFile,"%s %d",intName,&intVlan) == 2)
{
printf("In ctrlSend while loop");
}
fclose (pFile);
return 0;
}
UPDATE3: Seems like the file is not opening, looking into it.
When you do while (!feof ...) you check each time if you have reach the end of the file. However, at no point your advance in the file (fread ?). That means this will never terminate.
Check whether the file exists or not. You should always check whether File pointer is NULL or not after opening the file. I think your program is unable to open the file and you are trying to use the file pointer without checking which is causing undefined behavior.
I am working on a quadcopter project with Beaglebone.
I need help with using pwm on Beaglebone through a C program.
I have attached the following code,
#include <stdio.h>
#include <string.h>
#include <unistd.h>
struct pwm
{
char period[100];
char duty[100];
char polarity[100];
char run[100];
}pwm1,pwm2,pwm3,pwm4;
char pwm_1[]="P9_21";
char pwm_2[]="P9_14";
char pwm_3[]="P8_13";
char pwm_4[]="P9_42";
int initialize(struct pwm &pwmi, char pwm_i[])
{
sprintf(path,"echo \"bone_pwm_%s\" >> /sys/devices/bone_capemgr.9/slots",pwm_i);
fp = popen(path,"r");
fflush(fp);
usleep(1000);
sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/period",pwm_i);
fp = popen(path,"r");
while(fgets(path,100,fp)!=NULL)
strcpy(pwmi.period,path);
fflush(fp);
sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/duty",pwm_i);
fp = popen(path,"r");
while(fgets(path,100,fp)!=NULL)
strcpy(pwmi.duty,path);
fflush(fp);
sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/polarity",pwm_i);
fp = popen(path,"r");
while(fgets(path,100,fp)!=NULL)
strcpy(pwmi.polarity,path);
fflush(fp);
sprintf(path,"ls /sys/devices/ocp.3/pwm_test_%s.*/run",pwm_i);
fp = popen(path,"r");
while(fgets(path,100,fp)!=NULL)
strcpy(pwmi.run,path);
fflush(fp);
pclose(fp);
return 0;
printf("%s%s%s%s",pwmi.period,pwmi.duty,pwmi.polarity,pwmi.run)
}
int pwmperiod(struct pwm &pwmi, unsigned int period)
{
sprintf(path,"echo %d > %s", period, pwm.period);
fp = popen(path,"r");
usleep(1000);
pclose(fp);
return 0;
}
int main()
{
unsigned int period = 200000;
initialize(pwm1,pwm_1);
initialize(pwm2,pwm_2);
initialize(pwm3,pwm_3);
initialize(pwm4,pwm_4);
pwmperiod(pwm1,period);
return 0;
}
Now the above code works perfectly fine. But I want to use the pwmperiod() function a little differently. Instead of using popen() all the way, I want to use fopen() and fprintf() for the function pwmperiod() . Something like this,
int pwmperiod(struct pwm &pwmi, unsigned int period)
{
fp = fopen(pwmi.period,"r+");
fseek(fp,0,SEEK_SET);
fprintf(fp,"%d",period);
fclose(fp);
return 0;
}
I tried the modified code but when it attempts to write the period value, it outputs "segmentation fault".
I realized that fopen() takes a const char while pwmi.period is just char. Another problem popen() and sprint() are not compatible with const char.
So is there a way to resolve the conversion?
Also how often is popen() used in C/C++ programs?
PS:
Not an expert coder and I am not from a computer science background. I am learning progressively.
Again, the code works with popen() perfectly. But then I am comfortable with file handling in C. So I would prefer personally fopen() over popen() . Moreover I feel it would be pointless to use popen() in C. Might as well use a shell script for pwm.
Leaving aside for a moment the issue of char* vs. const char* (since a char* can anyway be passed to any function taking a const char*).
Have you checked that the return value from fopen is non-NULL?
Note that the file must exist when fopen is called with r+. If it doesn't, fopen will return NULL, generating a segfault.
Since the file is only being written, not read, consider using
fp = fopen(pwmi.period,"w");
which will create a new file if one doesn't already exist.
I am trying to read from a file specified in a command prompt through terminal using the line program < file.txt and then print it again to check it works. I get the error Segmentation fault: 11, I'm not sure if my file is opening correctly in my program.
This is the code so far:
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
Any help or feedback would be greatly appreciated.
You should execute your program like
./program file.txt
I'm not sure if my file is opening correctly in my program
Then you should really test for it, you are getting a segfault because fopen is returning NULL.
#include <stdio.h>
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
if (!fp) {
printf("Invalid file name \n");
return -1;
}
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
fopen is NULL because you are invoking the program in the wrong manner, < and > are a re-directions which can be useful but is not what you are trying to do in this case, correct way to invoke it is to simply pass it the arguments directly.
./program input.file
Yeah, either:
1) check the way you're invoking it, i.e,
check if the 'program' is an executable file, you can make it executable using chmod command in linux
check if the path to 'program' or 'file.txt' is correct
2) (I'm not sure of this): check if the content of 'file.txt' is of the right content. (I don't think it should affect to the extent that it causes a segmentation fault, but still, check it.)
Here is my code example:
int main(int argc, char* argv[])
{
char* fileName = "%appdata%\\log.log";
FILE *file;
file = fopen(fileName, "a+");
time_t startTime = time(0);
fputs("Started logging at: ", file);
fputs(ctime(&startTime), file);
fclose(file);
printf("%s", fileName);
return 0;
}
My program gets down to the printf() statement, and prints:
%appdata%\log.log
I know that is a viable location for a Windows computer, so why is the program unable to make the .log file? What is a workaround that I should use to make it work?
the fopen call has no idea what %appdata% is, as it can't magically convert that into a path. You have to expand the path yourself using the ExpandEnvironmentStrings function. e.g. (untested):
char dest[MAX_PATH];
ExpandEnvironmentStrings(fileName, dest, MAX_PATH);
file = fopen(dest, "a+");
%appdata%
is an environment variable, they are not automatically resolved and need their values to explicitly be retrieved using getenv function call.
We are working on a homework on CELL programming for college and their feedback response to our questions is kinda slow, thought i can get some faster answers here.
I have a PPU side code which tries to open a file passed down through char* argv[], however this doesn't work it cannot make the assignment of the pointer, i get a NULL.
Now my first idea was that the file isn't in the correct directory and i copied in every possible and logical place, my second idea is that maybe the PPU wants this pointer in its LS area, but i can't deduce if that's the bug or not. So...
My question is what am i doing wrong?
I am working with a Fedora 7 SDK Cell, with Eclipse as an IDE. Maybe my argument setup is wrong tho he gets the name of the file correctly.
Code on request:
images_t *read_bin_data(char *name)
{
FILE *file;
images_t *img;
uint32_t *buffer;
uint8_t buf;
unsigned long fileLen;
unsigned long i;
//Open file
file = (FILE*)malloc(sizeof(FILE));
file = fopen(name, "rb");
printf("[Debug]Opening file %s\n",name);
if (!file)
{
fprintf(stderr, "Unable to open file %s", name);
return NULL;
}
//.......
}
Main launch:
int main(int argc,char* argv[]) {
int i,img_width;
int modif_this[4] __attribute__ ((aligned(16))) = {1,2,3,4};
images_t *faces, *nonfaces;
spe_context_ptr_t ctxs[SPU_THREADS];
pthread_t threads[SPU_THREADS];
thread_arg_t arg[SPU_THREADS];
//intializare img_width
img_width = atoi(argv[1]);
printf("[Debug]Img size is %i\n",img_width);
faces = read_bin_data(argv[3]);
//.......
}
Thanks for the help.
I got it, if anyone else had issues with it you have to enable the upload rules and upload the extra-files you desired to be used by the simulator. :)
Exactly which line is failing, and how?
You should look at errno to see what error is being returned from fopen or other calls.
Also, it should not cause this problem, but you don't need the line:
file = (FILE*)malloc(sizeof(FILE));
That memory will just be leaked...