以下程式用 fgets() 取得一行文字便列印到螢幕上
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fPtr;
char s[50];
fPtr = fopen("oldname.txt", "r");
if (!fPtr) {
printf("檔案開啟失敗...\n");
exit(1);
}
while (fgets(s, 50, fPtr) != NULL) {
printf(s);
}
printf("\n");
fclose(fPtr);
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:cfgets.c
功能:示範 stdio.h 中函數 fgets() 的使用
作者:張凱慶
時間:西元2010年6月 */編譯後執行,結果如下

您可以繼續參考
輸出與輸入 stdio.h
- int getchar(void);
- char *gets(char *s);
- int putchar(int c);
- int puts(const char *s);
- int printf(const char *format, ...);
- int sprintf(char *s, const char *format, ...);
- int scanf(const char *format, ...);
- int sscanf(char *s, const char *format, ...);
- FILE *fopen(const char *filename, const char *mode);
- FILE *freopen(const char *filename, const char *mode, FILE *stream);
- int fflush(FILE *stream);
- int fclose(FILE *stream);
- int remove(const char *filename);
- int rename(const char *oldname, const char *newname);
- int fprintf(FILE *stream, const char *format, ...);
- int fscanf(FILE *stream, const char *format, ...);
- int fgetc(FILE *stream);
- char *fgets(char *s, int n, FILE *stream);
- int fputs(const char *s, FILE *stream);
- int fputs(const char *s, FILE *stream);
- size_t fread(void *ptr, size_t size, siz_t nobj, FILE *stream)
- size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream)
- int fseek(FILE *stream, long offset, int origin);
- long ftell(FILE *stream);
- void rewind(FILE *stream);
3 則留言:
hello,
printf(s) 再gcc compile時出現錯誤
應該改成print("%s",s)
請問使用 GCC 的版本是?我這邊用 GCC 4.0.1 編譯執行都 ok 的
while (fgets(s, 50, fPtr) != NULL)
我打這段不行,
如果我是這樣
fgets(s, 50, fPtr) 反而可以
張貼留言