0

can you tell me what adjustments i can do for my code, or any simplifications? What shouldn't i repeat, what should i change ? This code converts every word to upper case, if you find some problems,pls write in order to fix it))

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
    FILE * fPtr, *fPtr1;
    int c; /*to store characters*/
    char filename[20];
    char filename2[20] = "temp.txt";
    printf("Enter name of file: ");
    scanf("%19s%*c",filename);
    fPtr = fopen(filename, "r");
    fPtr1 = fopen(filename2, "w");
    c = fgetc(fPtr);
    while(c!=EOF){
        if(c!='\n'){
            if(islower(c)){
                fputc(c-32,fPtr1);
            }else{
                fputc(c,fPtr1);
            }
        }else{
            fputc(c,fPtr1);
        }
        c = fgetc(fPtr);
    }
    fclose(fPtr);
    fclose(fPtr1);
    remove(filename);
    rename(filename2,filename);
    fPtr = fopen(filename, "r");
    c = fgetc(fPtr);
    while(c!=EOF){
        printf("%c",c);
        c = fgetc(fPtr);
    }
    fclose(fPtr);
}
Kevin
  • 11
  • 4

2 Answers2

0

This program does what you say it does. But I recommend some changes that your future self will appreciate.

First, always initialize your variables; this habit will help to prevent odd bugs in your future code. Set ints to a value out of your expected range (e.g. maybe -1 in this case); set pointers to NULL; set char arrays to { '\0' } or to "\0".

Next, check your file pointers (fPtr, fPtr1) for NULL after fopen.

Finally, specific to this code, your check for new-line is unnecessary; islower will return 0 if the parameter is not a lowercase alphabetic character.

Shon
  • 71
  • 6
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX 20

char *mygets(char *s, size_t sz) {
  int ch;
  size_t i = 0;

  while((ch = getchar()) != '\n' && i < sz)
    s[i++] = ch;

  s[i] = '\0';

  return s;
}

int main(void) {
  FILE *fPtr;
  char filename[MAX+1];
  int c, i;

  printf("Enter name of file: ");
  mygets(filename, MAX+1);

  if(!strstr(filename, ".txt"))
    strcat(filename, ".txt");

  if((fPtr = fopen(filename, "r+")) == NULL) {
    fprintf(stderr, "Could not open %s\n", filename);
    exit(1);
  }

  i = 0;
  while((c = fgetc(fPtr)) != EOF) {
    fseek(fPtr, i, SEEK_SET);
    fputc(toupper(c), fPtr);
    i++;
  }

  rewind(fPtr);

  while((c = fgetc(fPtr)) != EOF)
    putchar(c);

  fclose(fPtr);

  return 0;
}