Want to create a file with write mode in C - c

I am new in C. I want to create a file in linux C program and write environment variables in it. If file already exist I want to open and append. I have written the following code.
char *envFile=getenv("FILENAME");
int fdEnv=-1;
fdEnv=open(envFile,O_CREAT,O_RDWR,O_APPEND);
printf("%d",fdEnv);
char** env;
if(fdEnv>0)
{
for (env = environ; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s",thisEnv);
write(fdEnv,thisEnv,strlen(thisEnv));
}
close(fdEnv);
}
But when I run it first time. A blank file is created. And it stays locked after execution. Looks like some error. Second time it fdEnv stays less than 0.
I really don't understand what is happening here. Please help.

Try using | to separate the flags.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
extern char **environ;
int main(void)
{
char *envFile = getenv("FILENAME");
int fdEnv = -1;
fdEnv = open(envFile, O_CREAT|O_RDWR|O_APPEND, 0644);
printf("%d\n", fdEnv);
int i = 0;
while (environ[i]) {
printf("%s\n", environ[i]);
write(fdEnv, environ[i], strlen(environ[i]));
char lf = '\n';
write(fdEnv, &lf, 1);
i++;
}
close(fdEnv);
return 0;
}
I've run above code on my linux computer and it works.

extern char **environ;
int main()
{
char **env;
char* filename = getenv("FILENAME")
const char* mode = "a";
FILE* file = fopen( filename, mode );
for ( env = environ; *env; ++env )
fprintf( file, "%s\n", *env );
fclose(file);
return(0);
}
You should think about handling when getenv fails, is blank, etc; let me know if you have any questions.

Related

How to capture the value of export and place it inside my program [duplicate]

I need to know a way for use environment variables in the C programming language. How can I use and read them?
For example, read an environment variable or take the value of an environment variable and load it in another variable.
You can use following functions -
char * getenv (const char *name)-returns a string that is the value of the environment variable name.
char * secure_getenv (const char *name)
Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
Use the getenv function from stdlib.h. That's it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test\n");
const char* s = getenv("PATH");
// If the environment variable doesn't exist, it returns NULL
printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");
printf("end test\n");
}
getenv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char* my_env_var = getenv("MY_ENV_VAR");
if(my_env_var)
printf("Var found: %s", my_env_var );
else
printf("Var not found.");
return 0;
}
On windows, you would use GetEnvironmentVariable.
#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
TCHAR buff[100] = T("");
DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);
if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
_tprintf(T("USERDOMAIN: %s\n"), buff);
} else if ( resultLengthInCharacters > 100) {
_tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
} else {
// Error handling incomplete, should use GetLastError(),
// but typically:
_tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
}
return 0;
}
But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)
Another way could be to use the global variable environ.
#include <stdio.h>
extern char** environ;
void main(int argc, char* argv[])
{
int i=0;
while(environ[i]!=NULL){
printf("%s\n",environ[i++]);
}
}

why doesn't this cgi script work, but it works perfectly as a a standalone program when executed in /var/www/cgi-bin/?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *cognome=NULL;
char *nome=NULL;
char *email=NULL;
char *password=NULL;
char *password2=NULL;
FILE *file_utenti=NULL;
file_utenti=fopen("Utenti.dat","a+");
struct utente
{
char cognome[25];
char nome[25];
char email[80];
char password[64];
char password2[64];
};
struct utente Utente;
file_utenti=fopen("Utenti.dat","r");
if(file_utenti!=NULL)
printf("%s\n","File aperto correttamente in lettura");
else
printf("%s\n","Impossibile leggere sul file utenti");
while(fread(&Utente, sizeof(Utente), 1, file_utenti))
{
printf("%s\t",Utente.cognome);
printf("%s\t",Utente.nome);
printf("%s\t",Utente.email);
printf("%s\t",Utente.password);
printf("%s\t",Utente.password2);
printf("\n");
}
fclose(file_utenti);
return 0;
}
If I run it as a cgi script, it doesn't enter the while, but it works perfectly if I run it in /var/www/cgi-bin/ directory. It opens the file, print all the records, and then quits
Of course, I used html tag in my cgi script. I mean, I used a table to show data from the file
But it only writes the tag table
The following proposed code:
cleanly compiles
performs the desired functionality
contains the suggested modifications in the comments to the question
it is a poor programming practice to include header files those contents are not used in the code. I.E. Suggest removing the statement: #include <string.h>
And now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct utente
{
char cognome[25];
char nome[25];
char email[80];
char password[64];
char password2[64];
};
struct utente Utente;
FILE *file_utenti=fopen("Utenti.dat","r");
if( file_utenti )
printf("%s\n","File aperto correttamente in lettura");
else
{ // fopoen failed
perror("Impossibile leggere sul file utenti");
exit( EXIT_FAILURE );
}
while(fread( &Utente, sizeof(Utente), 1, file_utenti) )
{
printf("%s\t",Utente.cognome);
printf("%s\t",Utente.nome);
printf("%s\t",Utente.email);
printf("%s\t",Utente.password);
printf("%s\t",Utente.password2);
printf("\n");
}
fclose(file_utenti);
return 0;
}
However, the question does not clarify if each string is terminated via a NUL byte. If not terminated by a NUL byte, then the code will output garbage.

C : how Get OS name ( Ubuntu, Debian,Centos,.. ) and if Definition OS name = ubuntu

I want to write a script with C. Only run on the Ubuntu system.
I Get the name of the operating system.
But. I failed to define the if clause.
Thanks for the help
Like this algorithm:
I think the most reliable way of checking the OS name is to use the uname utility.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int match_OS(const char* name) {
FILE *p;
int result;
char *s = malloc(1024);
p = popen("uname -v", "r");
s = fgets(s, 1024, p);
result = (strstr(s, name) != NULL);
pclose(p);
free(s);
return result;
}
int main() {
if (match_OS("Ubuntu")) {
puts("This is Ubuntu");
}
else {
puts("This isn't Ubuntu");
}
return 0;
}

Concatenate an environment variable and a string in C and feed to fopen()

I have very little knowledge about C and I can't get this simple task to work:
#include <stdio.h>
#include <string.h>
void load_hex_fw() {
char *warea = getenv("WORKAREA");
char hex[] = "/path/to/fw.hex";
char hexfile; // several trials done here (*hexfile, hexfile[500], etc.)
strcat(hexfile, *warea);
strcat(hexfile, hex);
printf("## %s\n", hexfile);
FILE *file = fopen(hexfile, "r");
fclose(file);
}
The above code basically opens a file for reading. But since the absolute path of the hex file is very long (and I'm also thinking of reusing this function in the future), I need to feed fopen() with a flexible hexfile variable. Googling string concatenation always gives me strcat(), or strncat, but I'm always getting a segmentation fault. I'm getting confused with pointers and references. Any help is greatly appreciated. Thanks in advance!
I have added some corrections and comments in your code, this should help you:
void load_hex_fw() {
char *warea = getenv("WORKAREA"); //check if getenv returns null
if(warea == NULL)
{
return;
}
char hex[] = "/path/to/fw.hex";
char *hexfile = NULL;//you need char buffer to store string
hexfile = malloc(strlen(warea) + stren(hex) + 1);//ENsure hexfile holds full filename
strcpy(hexfile,warea); //assuming you hold path in warea
strcat(hexfile, hex);//Assuming ypu hold filename in hex
printf("## %s\n", hexfile);
FILE *file = fopen(hexfile, "r");// check if fopen returns NULL
fclose(file);
free(hexfile);
}
asprintf allocates memory for you
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
void main() {
char *warea = getenv("WORKAREA");
if (!warea) {
warea = "default"; // or exit
}
char hex[] = "/path/to/fw.hex";
char *hexfile;
asprintf(&hexfile, "%s%s", warea, hex);
printf("## %s\n", hexfile);
// ...
free(hexfile);
}
it accepts 0 but result is hardly what you want for fopen
## (null)/path/to/fw.hex

How to use environment variable in a C program

I need to know a way for use environment variables in the C programming language. How can I use and read them?
For example, read an environment variable or take the value of an environment variable and load it in another variable.
You can use following functions -
char * getenv (const char *name)-returns a string that is the value of the environment variable name.
char * secure_getenv (const char *name)
Read about some more functions here -http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
Use the getenv function from stdlib.h. That's it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("test\n");
const char* s = getenv("PATH");
// If the environment variable doesn't exist, it returns NULL
printf("PATH :%s\n", (s != NULL) ? s : "getenv returned NULL");
printf("end test\n");
}
getenv:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char* my_env_var = getenv("MY_ENV_VAR");
if(my_env_var)
printf("Var found: %s", my_env_var );
else
printf("Var not found.");
return 0;
}
On windows, you would use GetEnvironmentVariable.
#include <stdio.h>
#include <winbase.h>
int main(int argc, char *argv[])
{
TCHAR buff[100] = T("");
DWORD resultLengthInCharacters = GetEnvironmentVariable(T("USERDOMAIN"), buff, 100);
if (resultLengthInCharacters > 0 && resultLengthInCharacters < 100) {
_tprintf(T("USERDOMAIN: %s\n"), buff);
} else if ( resultLengthInCharacters > 100) {
_tprintf(T("USERDOMAIN too long to store in buffer of length 100, try again with buffer length %lu\n"), resultLengthInCharacters);
} else {
// Error handling incomplete, should use GetLastError(),
// but typically:
_tprintf(T("USERDOMAIN is empty or not set in the Environment\n"));
}
return 0;
}
But if you are trying to get a standard path variable, you should use the SHGetFolderPath function with the right CSIDL variable (like from this question: How do I get the application data path in Windows using C++?)
Another way could be to use the global variable environ.
#include <stdio.h>
extern char** environ;
void main(int argc, char* argv[])
{
int i=0;
while(environ[i]!=NULL){
printf("%s\n",environ[i++]);
}
}

Resources