The10thDoctor
The10thDoctor

Reputation: 125

Opening files and changing file data to uppercase in C programming

I'am having some trouble with this code (see below). As regardless of what filename I enter, I get this gibberish " \330\370\277_\377 ". Can anyone tell me what I'am doing wrong? Any help would be greatly appreciated.

Thanks so much!

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

int main()
{
    char line[81], filename[21];
    int i;
    FILE *inFile;
    printf("\nPlease enter the name of a file: ");
    gets(filename);
    inFile = fopen(filename, "r");
    if(inFile == NULL)
    {
        printf("\nThe file %s was not successfully opened.", filename);
        printf("\nPlease check that the specified file exists.");
        getchar();
        exit(1);
    }
    while (fgets(line, 81, inFile) != NULL) 
printf("\n%s\n", line);

for (i = 0; line[i]; ++i) {
    line[i] = toupper(line[i]);

}
    printf("\nPrinted in UPPER case: \n\n");
    rewind(inFile);
    printf("\n%s", line);
    getchar();
}

Upvotes: 0

Views: 390

Answers (2)

sehe
sehe

Reputation: 393487

scanf("filename");

doesn't do what you hope. Look at the other scanf calls and the docs for clues. Here's an idea:

fgets(filename, sizeof(filename), stdin);

for (i = strlen(filename); i>0; --i)
{
    switch(filename[i-1])
    {
        case '\n':
        case '\r': filename[i-1] = '\0';
                   continue;
    }
    break;
}

Upvotes: 3

user123
user123

Reputation: 9071

One problem to note is with the indentation causing miscommunication between you and the compiler.

while (fgets(line, 81, inFile) != NULL)
    printf("\n%s\n", line);
for(i = 0; line[i]; ++i)
{
    line[i] = toupper(line[i]);
}

This is why I recommend always using braces:

while (fgets(line, 81, inFile) != NULL) {
    printf("\n%s\n", line);

    for (i = 0; line[i]; ++i) {
        line[i] = toupper(line[i]);
    }
}

Upvotes: 0

Related Questions