繁体   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