文本檔案只包含“hi”。我希望它指向 c 之后的下一個字符并列印它,但它卻給出了 h↑。
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;
}
uj5u.com熱心網友回復:
如果要在檔案內容上增加指標,則應讀取更多資料。一種簡單的方法是使用fread讀取一塊資料而不是getc讀取一個字符。例如:
#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;
}
uj5u.com熱心網友回復:
ch1 是堆疊上的一個變數,c 是用 ch1 的地址初始化的。在它上面使用后增量運算子不會在檔案上前進,而是在堆疊上前進。
要從檔案中讀取,您可以創建一個緩沖區并使用 fread 填充它,然后像您想要的那樣使用 char * 前進。
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;
}
uj5u.com熱心網友回復:
getc從檔案中只讀取一個字符。下次您呼叫getc它時,它將讀取以下字符。
c ;不會從檔案中讀取。它只會增加c指標,之后c將指向無效的記憶體位置。
不要讓事情變得比現在更復雜。
你想要這樣的東西:
#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;
}
要閱讀整個檔案,您需要:
#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;
}
在你的 C 學習材料中處理檔案的章節中解釋了關于EOF和為什么ch應該是的細節。int
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410871.html
標籤:
