【问题标题】:Read a file using "read()" function使用“read()”函数读取文件
【发布时间】:2020-11-07 23:17:29
【问题描述】:

我正在学习C,我需要读取一个文本文件,但我只能使用“write,malloc,free,open,read,close”。

这是我的代码:

#define MAXCHAR 10000

int open_fp(int check)
{
    char *int_vector;
    int fp,len;
    int i,j;
    char buffer[MAXCHAR]; 

    if(check == 0) //standard list
    {
        if((fp = open("file.txt", O_RDONLY)) != -1) //check if the fp is opened. -1 = error
        {
            printf("\n%d\n",fp); // DEBUG FUNCTION
            sleep(1);

            if (!(int_vector = (char*)malloc(sizeof(char) * sizeof(char))))
            {
                printf("\nWrong allocation\n!"); // DEBUG FUNCTION
                return(0);
            }
            len = read(fp,int_vector,MAXCHAR);

            for(i=0;i<len;i++)
            {
                printf("%c",int_vector[i]);
            } 
        }
        else
        {
            printf("File error!");
            return (0);
        }
        
    }
    return(0);
}

现在我的问题是:如您所见,

 char buffer[MAXCHAR];

我已经创建了静态缓冲区,但我想创建一个动态缓冲区,它允许我根据文本文件中的字符数调整缓冲区的大小,但我不知道如何......有人有诡计???????? ?

【问题讨论】:

  • 您可以使用malloc() 分配并使用realloc() 调整大小。如果您“不允许”使用realloc(),那么您可以分配另一个大小合适的缓冲区,复制数据,然后free() 第一个缓冲区。
  • ...或者您可以从一个小的(比如 1024 字节)缓冲区开始,并继续读取和重新分配,直到文件被读取。然后你最多有 1023 个字节未使用。
  • @Weather Vane 谢谢你的回复!不幸的是我不能使用 realloc 功能!还是谢谢你的回复!!
  • 我提到了你可以做的事情。
  • @WeatherVane 是的,我现在看到了!

标签: c malloc buffer fopen eof


【解决方案1】:

首先你分配内存的方式在下面一行是错误的。

//This allocates only 2 bytes of memory, but you are trying to read 10000
if (!(int_vector = (char*)malloc(sizeof(char) * sizeof(char))))

如下更正该行

//better to add one byte extra and store \0 at the end, useful in case of string operations
if (!(int_vector = malloc(MAXCHAR+1)))

就您的问题而言,在这种特殊情况下您不需要重新分配内存,因为您只是将字节读取到缓冲区并打印。

一个malloc 就足够了。

#include<stdlib.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAXCHAR 100

int open_fp(int check)
{
    char *int_vector;
    int fp,len;
    int i,j;
    char buffer[MAXCHAR]; 

    if(check == 0) //standard list
    {
        if((fp = open("file.txt", O_RDONLY)) != -1) //check if the fp is opened. -1 = error
        {
            printf("\n%d\n",fp); // DEBUG FUNCTION
            sleep(1);

            if (!(int_vector = (char*)malloc(MAXCHAR)))
            {
                printf("\nWrong allocation\n!"); // DEBUG FUNCTION
                return(0);
            }
            //not doing memset on purpose because only limited bytes are accessed.
            while(len = read(fp,int_vector,MAXCHAR))
            {
                printf("\n **number of bytes read is %d **\n",len);
                for(i=0;i<len;i++)
                {
                    printf("%c",int_vector[i]);
                } 
            }
            printf(" At last LEN = %d\n", len);

            //free the memory at the end
            free(int_vector);
            int_vector = NULL;
            close(fp);// better to as fd
        }
        else
        {
            printf("File error!\n");
            return (0);
        }
        
    }
    return(0);
}

int main()
{
    open_fp(0);
    return 0;
}

【讨论】:

  • 嘿@sravs!谢谢你,兄弟。我没看懂部分
  • 嘿@sravs!谢谢你,兄弟。我试图理解部分:while(len = read(fp,int_vector,MAXCHAR)),但我没有......如果缓冲区等于1024,程序是否只读取文本文件中的前1024个字符(?)
  • 没什么好讨论的,我已经尝试过这段代码,它可以工作。我明白你是如何在阅读中使用长度的。我刚刚改变了一些东西 while ((lenght = read(fc, &c ,1))) { i++; -其中 fc 是文件名 -c 被声明为 char -1 是要读取的字节,用于逐字节解析文本文件!
  • 函数:sleep()原型需要头文件:unistd.h
  • OT:关于:if (!(int_vector = (char*)malloc(MAXCHAR))) 在 C 中,返回的类型是 void*,可以分配给任何指针。强制转换只会使代码混乱(并且容易出错)。建议移除演员表
【解决方案2】:

嗯,如果你忘记设置realloc,这里是一些重新分配的示例代码(动态调整缓冲区)

    #include <stdio.h>
    #include <stdlib.h>
    
    int main () {
       char *str;
    
       /* Initial memory allocation */
       str = (char *) malloc(15);
       strcpy(str, "tutorialspoint");
       printf("String = %s,  Address = %u\n", str, str);
    
       /* Reallocating memory */
       str = (char *) realloc(str, 25);
       strcat(str, ".com");
       printf("String = %s,  Address = %u\n", str, str);
    
       free(str);
       
       return(0);
    }    

【讨论】:

  • 我认为mallocrealloc最好使用不同的变量,以防realloc失败,我们将丢失malloc分配的数据
  • @niek,sravs,谢谢你的回复!不幸的是我不能使用 realloc 函数!!
猜你喜欢
  • 2013-11-15
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多