簡體   English   中英

在C中讀取文本文件

[英]Reading a text file in C

我正在讀取文本文件,並嘗試在控制台上顯示其內容。 這是我的代碼:

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <fstream>

int main()
{
    FILE* fp=NULL;
    char buff[100];
    fp=fopen("myfile.txt","r");
    if(fp==NULL)
    {
        printf("Couldn't Open the File!!!\n");
    }
    fseek(fp, 0, SEEK_END);
    size_t file_size = ftell(fp);
    fread(buff,file_size,1,fp);
    printf("Data Read [%s]",buff);
    fclose(fp);
    return 0;
}

但是控制台上僅顯示冗余數據; 有人可以指出我的錯誤嗎?

完成此操作后,您忘記了將文件指針重置為啟動。

fseek(fp, 0, SEEK_END);

找到大小( file_size )之后執行此操作。

rewind (fp);

您需要先閱讀文件的開頭,然后再閱讀:

int main()
{
    FILE* fp=NULL;
    char buff[100];
    fp=fopen("myfile.txt","r");
    if(fp==NULL)
    {
        printf("Couldn't Open the File!!!\n");
        exit(1);                     // <<< handle fopen failure
    }
    fseek(fp, 0, SEEK_END);
    size_t file_size = ftell(fp);
    fseek(fp, 0, SEEK_SET);          // <<< seek to start of file
    fread(buff,file_size,1,fp);
    printf("Data Read [%s]",buff);
    fclose(fp);
    return 0;
}

試試吧....

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
printf("%s", line);
}

int main(int argc, char *argv[]) {
int size = 1024, pos;
int c;
char *buffer = (char *)malloc(size);

FILE *f = fopen("myfile.txt", "r");
if(f) {
  do { // read all lines in file
    pos = 0;
    do{ // read one line
      c = fgetc(f);
      if(c != EOF) buffer[pos++] = (char)c;
      if(pos >= size - 1) { // increase buffer length - leave room for 0
        size *=2;
        buffer = (char*)realloc(buffer, size);
      }
    }while(c != EOF && c != '\n');
    buffer[pos] = 0;
    // line is now in buffer
    handle_line(buffer);
  } while(c != EOF); 
  fclose(f);           
}
free(buffer);
return 0;

}

    #include "stdafx.h"
    #include <stdio.h>
    #include <string.h>
    #include <fstream>

    int main()
    {
        FILE* fp=NULL;
        char *buff;                     //change array to pointer
        fp=fopen("myfile.txt","r");
        if(fp==NULL)
        {
            printf("Couldn't Open the File!!!\n");
        }
        fseek(fp, 0, SEEK_END);
        size_t file_size = ftell(fp);
        buff = malloc(file_size);      //allocating memory needed for reading file data
        fseek(fp,0,SEEK_SET);          //changing fp to point start of file data
        fread(buff,file_size,1,fp);
        printf("Data Read [%s]",buff);
        fclose(fp);
        return 0;
    }

最好使用100字節的緩沖區來讀取文件,因為文件大小可能會超過100字節。

如果文件不是您想要使用fread讀取的元數據類型,則可以通過對文件執行fget來獲得更好的文件。

while循環中的fgets可用於檢查其到達的EOF或feof調用可用於檢查EOF。

fgets的示例代碼清單如下所示:

 while (fgets(buf, len, fp)) {
      printf("%s", buf);
 }

或與fgets一起使用的示例可能像這樣:

 while (fread(buf, len, 1, fp) >= 0) {
       printf("%s\n", buf);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM