Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

can someone show me the problem with this code

void GetFile(FILE* pt,char *pointer) { int counter=0,c=0; char chars; while ((chars=fgetc(pt))!=EOF) { if (chars=='\n') { counter++; } } fseek(pt,0,SEEK_SET); srand(time(NULL)); c = rand() % counter; counter=0; while(counter

MacBook Pro (13-inch, Mid 2012), OS X Mountain Lion (10.8.2)

Posted on Mar 9, 2013 4:00 AM

Reply
Question marked as Best reply

Posted on Mar 9, 2013 4:01 AM

First, format the code so we can read it.

5 replies

Mar 9, 2013 9:57 AM in response to etresoft

From the _C Programming FAQ_:


"If type char is signed and if EOF is defined as usual as -1, then the character with the decimal value 255 will be sign extended and will compare equal to EOF, prematurely terminating the input.


If type char is unsigned, an EOF value will be truncated and will *not* be recognised as EOF, resulting in infinite input."

Mar 9, 2013 11:15 AM in response to etresoft

While it's not good programing practice and heaven knows there is a lot wrong with the bit of code that can be seen, it will work.


int main(int argc, const char * argv[])

{


@autoreleasepool {

FILE *fp;

char chars;

if ((fp = fopen("/Users/frank/text.txt", "r" )) == NULL) {

NSLog(@"Open Failed");

return(-1);

}

while ((chars = fgetc(fp)) ) {

if (chars == '\n')

NSLog(@"new line\n");

else if (chars == EOF) {

NSLog(@"end of file\n");

return(EXIT_SUCCESS);

} else

NSLog(@"*%c*",chars);

}

NSLog(@"end of while");

}

return0;

}



produces

2013-03-09 13:40:38.402 ASCfgetcTST[10809:303] *a*

2013-03-09 13:40:38.404 ASCfgetcTST[10809:303] *b*

2013-03-09 13:40:38.404 ASCfgetcTST[10809:303] *s*

2013-03-09 13:40:38.404 ASCfgetcTST[10809:303] *c*

2013-03-09 13:40:38.405 ASCfgetcTST[10809:303] *e*

2013-03-09 13:40:38.405 ASCfgetcTST[10809:303] *f*

2013-03-09 13:40:38.406 ASCfgetcTST[10809:303] new line

2013-03-09 13:40:38.406 ASCfgetcTST[10809:303] *h*

2013-03-09 13:40:38.406 ASCfgetcTST[10809:303] *i*

2013-03-09 13:40:38.407 ASCfgetcTST[10809:303] *j*

2013-03-09 13:40:38.407 ASCfgetcTST[10809:303] *k*

2013-03-09 13:40:38.407 ASCfgetcTST[10809:303] new line

2013-03-09 13:40:38.408 ASCfgetcTST[10809:303] end of file


from a file of

cat text.txt

abscef

hijk


One nice thing about computers, you can ask them somehting and they will always tell you the truth (as far as their workings go)

can someone show me the problem with this code

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.