i want concatenate 2 strings config_path , config_file , pass string fopen(). problem fopen() returns error though 100% file exists. matter of fact, print string in command line before passing fopen(), , if copy string directly source code, fopen() finds file. what's problem here?
command line output
config: /nfs/stak/students/m/morriluk/.myshellrc|header: home unable open configuration file: no such file or directory source code
1 #define _posix_c_source 200908l 2 #define shell_bsize 1024 3 #define bsize 128 4 #define config_file "/.myshellrc" 5 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 #include <dirent.h> 10 #include <unistd.h> 11 #include <errno.h> 12 #include <sys/types.h> 13 #include <sys/wait.h> 14 15 char *warnings = "0"; 16 17 int main() 18 { 19 int i; 20 char buffer[bsize], *arg = null; 21 file *f; 22 char *config_path, *str, *config_file = config_file; 23 char *header = "home"; 24 25 config_path = getenv("home"); 26 27 str = malloc((strlen(config_path)+strlen(config_file))*sizeof(char)); 28 strcpy(str, config_path); 29 strcat(str, config_file); 30 31 printf("config: %s|header: %s\n", str, header); 32 33 (i = 0; < bsize; i++) 34 buffer[i] = '\0'; 35 36 if ((f = fopen(str, "r")) != null){ 37 38 } 39 else { 40 perror("unable open configuration file"); 41 } 42 return 0; 43 }
example program open file getting path env
openfile() { string filename; file *fp; filename = string(getenv("home")) + "/filename"; //home - configpath, replace file name fp = fopen(filename, "r"); if (fp == null ) cout<<"filename read failed"<<endl; /* write code perform task on file */ fclose(fp); //close handle } to test can make random file , try if fopen works other file in same path
if(fp=fopen("/nfs/stak/students/m/morriluk/testfile","r")) if above code not solve problem, let me know unix flavor , absolute file path name
Comments
Post a Comment