1

In the text.txt file, I have some lines like "Apples are red.guavas are green.lemons are yellow". I want the the first letters in new lines(g in guavas,l in lemons to be capital).But the output in the file is the same...

#include<stdio.h>
main()
{
  FILE *p;
  char c;
  int i;
  int end_of_line=0;
  p=fopen("text.txt","r+");//opening file for reading & writing.

  while(c!=EOF)
  {
    c=fgetc(p);
    if(end_of_line==1) // if it is a new line
    if (islower(c)!=0) // and if the first letter is small
      fputc(toupper(c),p); //change the small to capital
    if(c=='.')
      end_of_line=1;
    else
      end_of_line=0;
  }
  fseek( p, 0, SEEK_SET ); //setting the file pointer to the start of file
  while((c=fgetc(p))!=EOF)
    printf("%c",c);
  fclose(p);
}
Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
srk
  • 427
  • 4
  • 11
  • 27
  • 3
    Start by indenting your code. –  Oct 27 '13 at 07:11
  • 2
    this might help you http://stackoverflow.com/questions/3474254/how-to-make-a-first-letter-capital-in-c-sharp/3474346#3474346 – shakthydoss Oct 27 '13 at 07:14
  • @shakthydoss That link is for c#. – this Oct 27 '13 at 07:15
  • 2
    `fgetc` does **not** return a char. You should **not** store its value in a char. – Mat Oct 27 '13 at 07:16
  • @Mat , I agree but that won't be a problem as it is implicitly casted to character by C – srk Oct 27 '13 at 07:51
  • 2
    @srk: that's actually the problem. `EOF` is a value outside the range of `unsigned char`. http://pubs.opengroup.org/onlinepubs/009695299/functions/fgetc.html – Mat Oct 27 '13 at 07:51

1 Answers1

1

For files open for update (those which include a "+" sign), on which both input and output operations are allowed, the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a writing operation followed by a reading operation or a reading operation which did not reach the end-of-file followed by a writing operation.

I got your example working by using ftell anf fseek both before and after the line:

fputc(toupper(c),p);
DrYap
  • 6,525
  • 2
  • 31
  • 54
  • can you give me the exact fseek & ftell statements you used? – srk Oct 27 '13 at 08:32
  • `long x=ftell(p)-1;fseek(p,x,SEEK_SET); ... x=ftell(p);fseek(p,x,SEEK_SET);` This was just a hack, I don't know how safe the -1 is. You should read the documentation to get a better solution. – DrYap Oct 27 '13 at 10:12