Thread: Function is called and I am trying to open a file

  1. #61
    Registered User
    Join Date
    Mar 2004
    Posts
    78
    Thanks Rouss. I almost completed option 3. I converted the text file to lowercase. However, I now need to write the lowercase text to a new file and allow the user to name the output file. I used fputs, but it's not copying the file. Do I need to use the fopen statement again with the "w"?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    
    #define FLUSH while(getchar() != '\n')
    
    FILE *create(FILE*); /*function prototype*/
    void character(FILE*);
    void lower(FILE*);
    
    void main()
    {
    	int ch;
    	FILE *editor;
    	FILE*option2;
    	FILE*option3;
    
    	editor=NULL;
    	option2=NULL;
    	option3=NULL;
    
    	int calls[7] = {0};
    
    	ch = 0;
    	while(ch != -1)
    	{
    		printf("\n\nPlease choose an option below by typing a number between 1 and 8.\n\n");
    		printf("1\tCreate text file\n\n");
    		printf("2\tCount Characters,words and sentences\n\n");
    		printf("3\tConvert to lowercase\n\n");
    		printf("4\tConvert to uppercase\n\n");
    		printf("5\tEncrypt text\n\n");	
    		printf("6\tDecrypt text\n\n");
    		printf("7\tDisplay text file\n\n");
    		printf("8\tExit program\n\n");
    		scanf(" %d", &ch);
    		FLUSH;
    
    		if(ch > 0 && ch < 8) calls[ch-1]++;
    
    		switch(ch) {
    		case 1:
    			editor=create(editor);
    			break;
    		case 2:
    			character(option2);
    			break;
    		case 3:
    			lower(option3);
    			break;
    		}
    	}
    	fclose(editor);
    	return;
    
    }
    
    FILE *create(FILE *fname)
    {
    	char fileName[13];
    	char text[82];
    
    	printf("Enter the name of file to create: ");
    	fgets(fileName, sizeof(fileName), stdin);
    	fileName[strlen(fileName)-1] = '\0';
    
    	fname = fopen(fileName, "w");
    	if(fname == NULL)
    	{
    		printf("\nThe file cannot be opened.");
    		printf("\nPlease check that the file exists.");
    		exit(1);
    	}
    
    
    	printf("Enter the text to write to the file: ");
    	fgets(text, sizeof(text), stdin);
    	text[strlen(text)-1] = '\0';
    	 
    	fprintf(fname, "%s", text);
    
    	fclose(fname);
    
    	return fname;
    }
    void character(FILE *fname)
    {
    	char text[81];
    	char fileName[13];
    
    	int count,count1,i,j,k;
    	count=0,count1=0, i=0, j=0,k=0;
    
    	printf("\nPlease enter the name of the file you wish to open:  ");
    
    	fgets(fileName, sizeof(fileName), stdin);
    	fileName[strlen(fileName)-1]='\0';
    
    	fname=fopen(fileName, "r");
    	if (fname==NULL)
    	{
    	printf("\nThe file cannot be opened.");
    	printf("\nPlease check that the file exists.");
    	return;
    	}
    
    	while (fgets(text,81,fname) !=NULL)
             printf("\n%s", text);
    
    	for (i=0; text[i]!='\0';++i)
    	{	
    	count++;
    	}
    	printf("\n\nThe file you just opened:  %s,  has: %d characters, ", fileName,count);
    
    	int charNum = 0;
    	int numWords = 0;  
    	int inWord = 0;    
    
    	while (text[j] != '\0') 
    	{
        if ((text[j] == ' ') || (text[j] == '\t') ||
            (text[j] == '\n')) 
        {
              inWord = 0;
        } 
        else if (inWord == 0) 
        {
               ++numWords;
               inWord = 1;
            } 
            ++j;
        }        
    	printf("%d words, and ", numWords);
    
    	for (k=0; text[k] !='\0';++k)
    	{
    	if (text[k]=='.')
    	{
    	count1++;
    	}
    	
    	}
    	printf("%d sentences.\n", count1);
    
    }
    void lower(FILE *fname)
    {
    
    	char text[81];
    	char fileName[13];
    
    	int c;
    
    	printf("\nPlease enter the name of the file you wish to open:  ");
    
    	fgets(fileName, sizeof(fileName), stdin);
    	fileName[strlen(fileName)-1]='\0';
    
    	fname=fopen(fileName, "r");
    	if (fname==NULL)
    	{
    	printf("\nThe file cannot be opened.");
    	printf("\nPlease check that the file exists.");
    	return;
    	}
    
    	while ((c=getc(fname)) != EOF)
        putchar(tolower(c));
    
    	while (fgets(text,81,fname) !=NULL)
             printf("\n%s",text);
    
        printf("\nWhat name would you like to call the new lowercase file:  ");
    
             fgets(fileName, sizeof(fileName), stdin);
            fileName[strlen(fileName)-1]='\0';
    
           fputs(fileName,fname);	
    }
    ****************************boss1.txt************* ***********************
    Lets try this one more time.I want three sentences.This is the third one.

    ************************************************** ***********************
    /*
    Please choose an option below by typing a number between 1 and 8.

    1 Create text file

    2 Count Characters,words and sentences

    3 Convert to lowercase

    4 Convert to uppercase

    5 Encrypt text

    6 Decrypt text

    7 Display text file

    8 Exit program

    3

    Please enter the name of the file you wish to open: boss1.txt
    lets try this one more time.i want three sentences.this is the third one.

    Please choose an option below by typing a number between 1 and 8.

    1 Create text file

    2 Count Characters,words and sentences

    3 Convert to lowercase

    4 Convert to uppercase

    5 Encrypt text

    6 Decrypt text

    7 Display text file

    8 Exit program
    */

  2. #62
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131

    Here's what you need

    First, declare a new FILE *.
    FILE *lower;

    Then after you get the new filename
    lower = fopen(fileName, "w");

    I would say get the lowercase filename, open the lowercase file, then try this
    Code:
    int i;
    fgets(text, 81, fname);
    text[strlen(text)-1] = '\0';
    while(!feof(fname))
    {
    	for(i = 0; i < strlen(text); i++)
    	{
    		if(isupper(text[i]))
    			text[i] = tolower(text[i]);
    	}
    	fprintf(lower, "%s\n",text); /* Could use fputs but this works too */
    	fgets(text, 81, fname);
    	text[strlen(text)-1] = '\0';
    }
    Try that. If you want to see if it is working, just use a puts(text) before the fprintf()

    Later.

  3. #63
    Registered User
    Join Date
    Mar 2004
    Posts
    78
    The new file that I named is created with the correct name that I chose, but when I open the file, it's empty. Not sure why.

    Code:
    void lower(FILE *fname)
    {
    	FILE *lower;
    
    	char text[81];
    	char fileName[13];
    
    	int i;
    
    	printf("\nPlease enter the name of the file you wish to open:  ");
    
    	fgets(fileName, sizeof(fileName), stdin);
    	fileName[strlen(fileName)-1]='\0';
    
    	fname=fopen(fileName, "r");
    	if (fname==NULL)
    	{
    	printf("\nThe file cannot be opened.");
    	printf("\nPlease check that the file exists.");
    	return;
    	}
    	
    	printf("\nWhat name would you like to call the new lowercase file:  ");
    	 
    	lower = fopen(fileName, "w");
    
    	fgets(text, 81, fname);
    	text[strlen(text)-1] = '\0';
    	while(!feof(fname))
    	{
    	for(i = 0; i<strlen(text); i++)
    	{
    		if(isupper(text[i]))
    			text[i] = tolower(text[i]);
    	}
    	fprintf(lower, "%s\n",text); /* Could use fputs but this works too */
    	fgets(text, 81, fname);
    	text[strlen(text)-1] = '\0';
    
        fclose(lower);
    
    }

  4. #64
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Any "new file" you open is going to be empty. Also note that you open with "r", which is for reading, and not writing.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #65
    Registered User
    Join Date
    Mar 2004
    Posts
    78
    I am opening a file first, then converting to lowercase.
    After converting the file to lowercase, I need to write the lowercase text to a new file. So wouldn't I use the "w" to write?

  6. #66
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    From what I can see... You need fclose(fname) with the fclose(lower) ... And you're while loop is missing the closing }, which should be before the fclose(lower)

  7. #67
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>while(!feof(fname))
    Bad idea.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  8. #68
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    Hammer,

    I know the while(!feof(fname)) is a bad idea for the reasons in FAQ, also learned why in class, but we we taught that if you read once before the loop, then inside the loop do whatever you need with the data, and read from the file just before the end of the loop, it would work correctly. Is this correct? Or does it only work sometimes? It's always worked for me in the past.

  9. #69
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>Is this correct?
    No, it is not correct. A read error could occur whilst you're in the middle of a file, the eof bit won't necessarily be set (unless someone can show me otherwise).

    Also, look here:
    Code:
      fgets(text, 81, fname);
      text[strlen(text)-1] = '\0';
    This is a bug straight away, strlen in being invoked on a buffer that has undefined contents. If fgets() had failed, what value would text hold? How do you know its safe to use strlen?

    Besides, you're writing the same line of code twice, why bother? Just check the return value from fgets() and you'll be safe.

    As side note:
    text[strlen(text)-1] = '\0';
    Don't assume that fgets() put a \n into the array, for it might not have.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  10. #70
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    Thanks for the explanation. So, instead of assuming the fgets will get the '\n', it would be safer to us
    Code:
    if(string[strlen(string) - 1] == '\n')
        string[strlen(string)-1] = '\0';

  11. #71
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    There are plenty of ways, yours works, but is inefficient because you call strlen twice (which walks the length of the array twice).

    Ways I use are:
    Code:
     char *p;
     
     if ((p = strchr(text, '\n')) != NULL)
       *p = '\0';
    or, when my fingers are feeling lazy:
    Code:
     strtok (text, "\n");
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  12. #72
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    Hmm, thanks, I'll have to write those methods down.

    Thanks again,
    Rouss

  13. #73
    Registered User
    Join Date
    Mar 2004
    Posts
    78
    while(!feof(fname))...Take this code out then

  14. #74
    I like code Rouss's Avatar
    Join Date
    Apr 2004
    Posts
    131
    Look on the link hammer put in his first post.
    It says to write it like this
    while (fgets(buf, sizeof(buf), fp) != NULL)
    {
    ...
    }

    Then you wouldn't need the read at then end either... Ofcourse, change buf to text, and fp to fname...

  15. #75
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    A new point, brought to my attention:
    Code:
    if(isupper(text[i]))
    	text[i] = tolower(text[i]);
    No need to call isupper(), just go straight for tolower(). If it's already lower case, or just not an upper case letter, it won't hurt, the character's value will remain unchanged.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed