c - 如何保存文件内容

标签 c file-io

感谢您的回答,但在此之前我的代码可以从文件中读取并打印出该区域中的值!我的问题是如何在“FOR LOOP”之外使用这些值。因为我不想在需要值的时候继续读取文件,假设数组 data[][] 包含文件的所有内容......是否可以在循环及其打印之外调用数组输出所有文件内容?

//file
S (20,22)(129,37)
S (10,18)(40,200)
S (10,20)(39,15)
S (30,400)(750,200)
S (160,70)(240,20)
S (40,40)(10,39)
S (6,65)(94,2)
S (404,40)(110,39)
S (86,61)(50,19)

  //part of code.........

      int count=1;   

       for (i=0; i <= count; i++)
       {
         while(fscanf(file, "S (%d,%d)(%d,%d)\n", &a, &b, &c, &d) !=EOF)
         {

 data[i][0] =a;
 data[i][1] =b;
 data[i][2] =c;
 data[i][3] =d;

 printf("%d,%d,%d,%d\n",data[i][0], data[i][1], data[i][2], data[i][3]);
  XDrawLine(display_ptr, win, gc_grey,a, b, c, d);

    count++;
   }

 // want to call the array data[i][j] here outside the iteration above..
  int j1=0;  
       for (i=0; i <= 19, j1<=3; i++) {
        printf("%d\n",data[i][0]);

        } 

最佳答案

你永远不会在循环中增加i。而且,外层循环什么也不做。

尝试这样的事情:

int i;

for (i = 0; fscanf(...) != EOF; ++i)
{
    // if i == current array size of data, reallocate or break

    data[i][0] = a;
    data[i][1] = b;
    data[i][2] = c;
    data[i][3] = d;

    // etc.
}

// Now data[k] holds data for k in [0, i)

您必须考虑当文件中的行数多于数组元素时会发生什么。您可以重新分配(如果数组是动态的),也可以将整个构造包装在另一个循环中,该循环以 block 的形式处理文件。您还应该检查 fscanf 操作是否成功提取所有数据!

关于c - 如何保存文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12582113/

相关文章:

c - 为什么以下不将数组内容写入文件

c++ - 使用相对路径读取文本文件

c - 如何在文件中间插入和删除一些字符?

c++ - 生成文件 : Is there are a general way to show which line from makefile is causing the error?

c - Linux fork() 和 wait()

C、Little和Big Endian混淆

c - C 中文件的输入和输出

C 服务器和客户端 - 段错误并显示垃圾

从文件中计算矩阵中的岛屿

java - 从 HDFS 下载大文件