2016-4-6工作日志:C读取文本文件

来源:互联网 发布:创远家居系统源码 编辑:程序博客网 时间:2024/05/16 19:16

之前接触过Java读取文本文件的问题,这次记录一下怎样用C读取文本文件。以前上C语言这门课的时候翘了不少课,所以指针和文件操作学得不太好。真是出来混总是要还的,翘课不可取。

下面是一段简单的代码,功能是从一个文件中读取数据,然后写入另一个文件。有些头文件这里用不着,我懒得改了。

#include <opencv2/highgui/highgui.hpp> #include <stdio.h>#include <stdlib.h>#include "stdafx.h"#include "time.h"using namespace std;     FILE   *stream;          void   main(   void   )     {          int a=0;   int b=0;   int c=0;   int d=0;          stream   =   fopen(   "file.txt",   "r"   );           if(   stream   ==   NULL   )            printf(   "The   file   was   not   opened\n"   );           else           {                 fscanf(   stream,   "%d%d%d%d",  &a,&b,&c,&d );     int x[4]={a,b,c,d};  for(int n=0;n<4;n++)  {  printf("%d",x[n]);  printf("\n");  }              fclose(   stream   );     FILE* fp;  fp = fopen("file_.txt","a");  for(int t3=0; t3<4; t3++){fprintf(fp, "%d ",x[t3]);}  fclose(fp);        }   }   

原文件中只有一行数据,是4个整数。这段代码把这4个数分别读给a,b,c,d,然后写入file_.txt文件中。

0 0
原创粉丝点击