0

I want to print the data stored in a file which is randomly cased in all caps and strupr() seems to be something that's been listed by someone previously but its not a standard function and may not be cross platform. Is there something which is cross platform?

EDIT 1:

                                fgets(input1,254,title);
                                fgets(input2,254,author);
                                input1[strcspn(input1, "\n")] = '\0';
                                input2[strcspn(input2, "\n")] = '\0';
                                printf("<%s> <%s>\n",input1,input2 );

I want to print the string stored in input1 and input2 in uppercase. How to do that?

3 Answers3

1

You can process character by character and use toupper(). Standard function C89 onwards.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You can use a custom made function, f.e. upcase(). It reads every character in the file, checks whether it is lowercase or not (if it is, the character is adjusted to uppercase using the toupper() function), stores the whole file content into a buffer and then overwrites the file with the content in the buffer:

FILE* upcase (const char* path)
{
    int c, cnt = 0, i = 0, j = 1;
    int n = 500;
    FILE* fp = fopen(path, "r+");

    char* buffer = calloc(n, sizeof(char));

    if (!fp || !buffer)
    {
       return NULL;
    }

    while ((c = fgetc(fp)) != EOF)
    {  
       if ( i == n )
       {
           j++;
           realloc(buffer, sizeof(char) * (n * j));

           if (!buffer)
           {
               return NULL;
           }

           i = -1;
       }  

       c = toupper(c);
       buffer[i] = c;

       i++;
       cnt++;
    }

    for ( int i = 0; i < cnt; i++ )
    {
        if (fputc(c, fp) == EOF)
        {
            fclose(buffer);
            return NULL;
        }
    }

    return fp;    
}
0

Or you can check if character is in between a & z then do a - 32. It will be changed to capital letter.

Here a - 32 = A, because ASCII value of a is 97 and 97 - 32 = 65 and we all know that ASCII value of A is 65.

Code:

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

int main(void)
{
    FILE *fp;
    char buffer[255] = {'\0'}, c;
    int i = 0;

    fp = fopen("txt.txt", "r");

    if(!fp)
    {
        perror("txt");
        exit(1);
    }

    while( (c = getc(fp)) != EOF)
        buffer[i++] = c;

    for( i = 0; buffer[i] != '\0'; i++)
    {
        if(buffer[i] >= 'a' && buffer[i] <= 'z')
            buffer[i] = buffer[i] - 32;
        printf("%c", buffer[i]);
    }
    fclose(fp);
    return 0;
}

Output:

HELLO!
THIS IS 2ND LINE.
Shubham
  • 1,153
  • 8
  • 20