I need help with C strings!

sylverfyst@gmail.com's Avatar, Join Date: Oct 2009
Newbie Member
I'm trying to read strings in from a file that was inputed from the user and print them on separate lines I need to make sure that there are no non printable characters in the string. if there are non printable characters skip to the next string. A string in this should be greater than 4 characters and null terminated. I have:

Code:
#include <stdio.h>
#include <string.h>
char fname[150];
char *p;
FILE *in_file;

int main(){
     printf("Enter a filename: ");
     if(fgets(fname,sizeof(fname),stdin) != NULL){
          if((p=strchr(fname, '\n')) != NULL)
                *p = '\0'
     }
     in_file = fopen(fname,"r");
     if(in_file == NULL){
         printf("Cannot open %s \n", fname);
         exit(8);
     }
This opens the file for reading. I assume that a function to read a string that does not contain a non printable character and print it, in a loop would work fine here, but I don't know how to check if there are non printable characters/ skip to the next string. I feel like a noob lol
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
isprint() checks if a character is printable. It returns TRUE or FALSE.
0
sylverfyst@gmail.com's Avatar, Join Date: Oct 2009
Newbie Member
thank you that helps quite a bit, now I just need to check if the string is greater than 4 characters and print it, if not call the function again and skip to the next string.
0
sylverfyst@gmail.com's Avatar, Join Date: Oct 2009
Newbie Member
so I worked it out partially and I thought it should work, but my code isn't for some reason or another. here is my code as it stands.

Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char fname[100];
char *p;
FILE *in_file;
 
void get_strings(FILE *fp){
 char str[100];
 char ch;
 char ch2;
 
 ch = fgetc(fp);
 while(ch != EOF){
  while(isprint(ch) != 0){
   strcpy(str,ch);
   ch2 = fgetc(fp);
   if(strlen(str) > 4 && isprint(ch2) == 0) {
    printf("%s \n",str);
    break;
   }
   else
    ch = ch2;
  }
  ch = fgetc(fp);
 }
}
 
int main(int argc, char *argv[])
{
 printf("Enter a filename: ");
 if(fgets(fname,sizeof(fname),stdin) != NULL){
  if((p = strchr(fname, '\n')) != NULL)
   *p = '\0'
 }
 in_file = fopen(fname, "r");
 if(in_file == NULL){
  printf("Cannot open %s \n", fname);
  exit(8);
 }
 get_strings(in_file);
}
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
"Doesn't work" isn't much of a description. How exactly doesn't it work would be useful.

Anyway, here's one error: strcpy(str,ch);
strcpy takes two strings, not a string and a char.

Your logic is incorrect for testing the length of the printable string. You should collect characters until you hit a non-printable character (or EOF or the maximum size of str), THEN test the length, and display it if needed. Currently the code checks the length within the collection loop, which means the loop will terminate as soon as the length exceeds 4.