Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove new line character

Status
Not open for further replies.
May 3, 2002
633
0
0
US
Below is some of the code in my small program. The problem is when trying to do a remove() or unlink() it errors out and does not remove the file. The problem is when I try to print the argument as say, "xxx /path/file xxx" it is doing:
"xxx /path/file
xxx"

And a strlen() returns one more than the actual length, say /path/file should return 10 it prints 11. So I am thinking it is "/path/file\n\0" instead of "/path/file\0"

So how do I remove the \n at the end of the string? Thanks!

The code:

main() {
setuid(0);
setgid(0);
system("find /home /tmp /usr/WebSphere -type f -name core > /tmp/findcore.txt");
line=0;
inf = fopen ("/tmp/findcore.txt", "r");
if (inf == NULL) printf("Can't Open File\n");
else {
while (fgets(s, 79, inf) != NULL) {
line++;
printf("File %d: %s", line, s);
Confirm(s);
}
}
}

Confirm(char *s) {
char ch;
int valid_choice;
int status; /* added for error checking */
extern int errno; /* added for error checking */

printf("Confirm deletion of file %s", s);
valid_choice = 0;
while( valid_choice == 0 ) {
printf("Continue (Y/N)? ");
scanf(" %c", &ch );
ch = toupper(ch);
if(ch == 'Y') {
printf("filename has %d letters\n", strlen(s));
status = remove(s);
valid_choice = 1;
}
else if(ch == 'N') {
printf("filename has %d letters\n", strlen(s));
valid_choice = 1;
}
else
printf("\007Error: Invalid choice\n");
}
else
printf("\007Error: Invalid choice\n");
cleartoendofline();
printf("status values: remove func (%d), errno (%d)\n", status, errno); /*add
ed for error checking*/
printf("\n");
}
}


 
Here is some sample code just to demonstrate:

Code:
#include <stdio.h>
#include <stdlib.h>

#define LEN 100

int main(int argc, char **argv) {
int i = 0;
char buf[LEN];
FILE *fdf;


     if (argc != 2) {
        printf(&quot;Error: Illegal args.\n&quot;);
        return 1;
     }

     if ( (fdf = fopen(argv[1],&quot;r&quot;)) != NULL) {
           while ( (fgets(buf,100,fdf)) != NULL) {
                    for (i=0 ; i <= strlen(buf) ; i++) {
                        if (buf[i] == '\n') {
                            printf(&quot;Changing at %d string length %d\n&quot;, i, strlen(buf));
                            buf[i] = '\0';
                            printf(&quot;New string: %s\n String length now: %d\n&quot;, buf, strlen(buf));
                        }
                    }
           }     
      } else {
        perror(&quot;Opening file&quot;);
        return 1;
      }
return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top