在用C语言中,如何将一个二维数组存储到文本文件中?

2024-11-07 16:40:31
推荐回答(4个)
回答(1):

fwrite 用于写 2 进制文件。用 fprintf 就可以了。
int a[4][5]={1 ,2,2,3,4,2,4,7,9,0,5,6,7,8,3,5,8,6,2,1};
FILE *fout;
int i,j;
fout = fopen("abc.txt","w"); // 打开文件,文本输出文件
for (j=0;j<4;j++){
for (i=0;i<5;i++){ fprintf(fout,"%d ",a[j][i]);} // 写
fprintf(fout,"\n");
}
fclose(fout); //关闭

回答(2):

完整代码:

#include

int array[4][5];

int main(){
freopen("a.txt","w",stdout);
for(int i=0;i<4;i++){
for(int j=0;j<5;j++){
printf("%d ",array[i][j]);
}
printf("\n");
}
return 0;
}

回答(3):

FILE *fp;
fp=open("my.txt","w");
if(fp!=NULL)
{
for(i=0;i<4;i++)
for(j=0;j<5;j++)
fprintf(fp,"%d",array[i]);
}

回答(4):

  可以这样:
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Windows.Forms;
  using System.IO;
  using System.Collections;
  
  namespace WindowsFormsApplication2
  {
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }
  
  private void button1_Click(object sender, EventArgs e)
  {
  int line = 0;
  string strLine="";
  FileStream fs;
  OpenFileDialog openf = new OpenFileDialog();
  openf.InitialDirectory = "c:\\";
  openf.Filter = "exe files (*.txt)|*.txt";
  openf.FilterIndex = 2;
  openf.RestoreDirectory = true;
  if (openf.ShowDialog() == DialogResult.OK)
  {
  try
  {
  fs = new FileStream(openf.FileName, FileMode.Open);
  StreamReader m_streamReader = new StreamReader(fs);
  m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
  do
  {
  strLine = m_streamReader.ReadLine();
  line++;
  
  } while (strLine != null && strLine.Length > 0);
  
  string[,] array = new string[line, 4]; // 声明输出数组
  m_streamReader = new StreamReader(fs);
  m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
  line = 0;
  do
  {
  strLine = m_streamReader.ReadLine();
  if (strLine!=null && strLine.Contains('|'))
  {
  string[] spli = strLine.Split('|');
  array[line, 0] = spli[0];
  array[line, 1] = spli[1];
  array[line, 2] = spli[2];
  array[line, 3] = spli[3];
  line++;
  }
  
  } while (strLine != null && strLine.Length > 0);
  
  string temp = "";
  for (int i = 0; i < line; i++)
  {
  temp = temp + array[i, 0];
  temp = temp + "|" + array[i, 1];
  temp = temp + "|" + array[i, 2];
  temp = temp + "|" + array[i, 3] + "\n";
  }
  MessageBox.Show(temp);
  
  }
  catch (System.Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  }
  
  }
  }
  }