text file only contain "hi".I expected it to point to the next charecter after c and print it but it's giving h↑ instead.
int main()
{
FILE *ptr;
char ch1;
ptr = fopen("rough.txt", "r");
ch1 = getc(ptr);
char *c = &ch1;
printf("%c", *c);
c ;
printf("%c", *c);
return 0;
}
CodePudding user response:
If you want to increment a pointer over the contents of the file, you should read more data. A simple way to do that is to use fread to read a chunk of data rather than getc, which only reads one character. For example:
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
const char *path = argc > 1 ? argv[1] : "rough.txt";
FILE *ifp = fopen(path, "r");
if( ifp == NULL ){
perror(path);
return 1;
}
char buf[128];
char *c = buf;
size_t read_count = fread(buf, sizeof(char), sizeof buf, ifp);
while( c < buf read_count ){
putchar(*c );
}
return 0;
}
CodePudding user response:
ch1 is a variable on the stack, and c was initailized with address of ch1. using the post increment operator on it wont advance on the file but on the stack.
To read from the file you can create a buffer and use fread to fill it up then advance on it with the char * like you wanted to.
int main()
{
FILE *ptr = NULL;
char buff[DESIRED_BUFF_SIZE] = {0};
ptr = fopen("rough.txt", "r");
fread(buff, <amount of chars to be read>, sizeof(char), ptr);
/* print the chars from the buffer here*/
return 0;
}
CodePudding user response:
getc reads exactly one character from the file. Next time you call getc it will read the following character.
c ; will not read from the file. It will only increment the c pointer, after which c will point to an invalid memory location.
Don't make things more complicatd than they already are.
You want something like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* inputfile;
char ch;
ptr = fopen("rough.txt", "r");
if (ptr == NULL) // you need to check if fopen succeeded
{
printf("File could not be opned\n");
return 1;
}
ch = getc(inputfile); // read first character
printf("%c", ch);
ch = getc(inputfile); // read second character
printf("%c", ch);
fclose(inputfile); // and don't forget to close
return 0;
}
To read the whole file you need this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* inputfile;
int ch; // must be an int so that EOF works
inputfile = fopen("rough.txt", "r");
if (inputfile == NULL) // you need to check if fopen succeeded
{
printf("File could not be opned\n");
return 1;
}
while ((ch = getc(inputfile)) != EOF)
{
printf("%c", ch);
}
fclose(inputfile);
return 0;
}
The details about EOF and why ch should be an int are explained in the chapter dealing with files in your C learning material.
