When I run this program. The file descriptor returns -1
value and hence the program terminates. I don't know why is this happening. As the pid value is exactly the name of the file that I want to open.
const char *psyn = "product/productId:";
char line[100];
pFile = fopen ("pids.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
while(fgets (line , sizeof(line) , pFile))
{
if (strstr(line, psyn) == line)
{
leng = strlen(line);
if( line[leng-1] == '\n' )
line[leng-1] = 0;
if( line[0] == '\n' )
line[0] = 0;
pid = line+strlen(psyn)+1;
strcat(pid,t);
leng = strlen(pid);
if( pid[leng-1] == '\n' )
pid[leng-1] = 0;
fd = open(pid, O_RDWR, 0644);
if (fd == -1)
cout<<"eror in file \n";
else { //.. rest of the program}
pid = line+strlen(psyn)+1;aroused my suspicions. First strlen() here is not efficient. Second the +1 is one longer than the string.
int opt_verbose; // from -v option char psyn[] = "product/productId:"; // array, not pointer char line[100]; FILE *pFile = fopen ("pids.txt" , "r"); if (pFile == NULL) perror ("Error opening file"); else { while(fgets (line , sizeof(line) , pFile)) { char *s = strstr(line, psyn); if ( s == line) { int leng; for ( leng = strlen(line); leng > 0 && isspace(line[leng-1]); leng-- ) line[leng-1] = '\0'; char *pid = line + sizeof(psyn) - 1; // sizeof without \0 strcat(pid,t); leng = strlen(pid); if( pid[leng-1] == '\n' ) pid[leng-1] = 0; if ( opt_verbose ) printf( "VERBOSE: opening %s\n", pid ); int fd = open(pid, O_RDWR, 0644); if (fd == -1) { // perror is usually not sufficiently detailed printf( "ERROR: open \"%s\" failed: (%d) %s\n", pid, errno, strerror(errno) ); // \"%s\" nicely shows unexpected spaces in paths. continue; }