c - C 上的文件操作

标签 c file

我将动态数组写入文件。(100 宽度)并且我从文件中读取它。

但我意识到我无法读取从内存中分配的所有元素。

我的代码示例如下:

main()
{
    FILE *file;
     int *numbers;
     int *numbers2;

     numbers = (int *)malloc(100*sizeof(int));
     numbers2 = (int *)malloc(100*sizeof(int)); 


    int i,j,tane;

    file=fopen("numbers.txt","w++");

    for(i=0;i<100;i++)
    { numbers[i]=i;}

    if(file==NULL)
    {printf("Error:File cannot open \n");
     return 1;
    }


    else {
          fwrite(numbers,4,100,file);

         }
    rewind(file);

    printf("Numbers read from file:\n");
    tane=fread(numbers2,4,100,file);
    for(i=0;i<tane;i++)
    { printf("%d ",numbers2[i]);}


    fclose(file);
    getch();
}

我看到 C 打印了 0-25 个元素。 我无法理解所有元素都没有打印。(0 到 100)

你能帮我一下吗?

最诚挚的问候...

最佳答案

您正在以文本模式打开文件,但正在写入二进制数据。尝试使用 fopen("numbers.txt", "wb+") 代替。

关于c - C 上的文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5811573/

相关文章:

c - 为什么 Xcode 无法在我的 Macbook Pro 上运行?

php - 磁盘上文件的随机名称 sha1 或 uniqid 哪个更好?

c# - 使用 NUnit 进行测试时应该如何处理数据文件?

linux - 为什么在 bash 命令后附加控制字符?

c++ - GCC C++ 11无法看到#if Windows和#if linux(重新询问)

c - 解析字符串并将 token 的索引放入表中

c - 如何传递和接收指向结构数组的指针?

c - 如何在 IBM i-series (AS/400) 上查找对应于 CHGJOB INQMSGRPY(*DFT) 的 ILE C 函数

java - 如何逐行打印字符串对象

使用 getc 从文件读取时检查字符