C和C++文件操作

C/C++文件操作汇总

1.判断文件夹或者文件是否存在

C语言判断文件夹或者文件是否存在的方法

_access

函数原型: int access(const char *filename, int mode);access函数已经被弃用;可用_access替换

所属头文件:io.h

filename:可以填写文件夹路径或者文件路径

mode:0 (F_OK) 只判断是否存在

​ 2 (R_OK) 判断写入权限

​ 4 (W_OK) 判断读取权限

​ 6 (X_OK) 判断执行权限

用于判断文件夹是否存在的时候,mode取0,判断文件是否存在的时候,mode可以取0、2、4、6。 若存在或者具有权限,返回值为0;不存在或者无权限,返回值为-1。

““

include

include

fopen

函数原型:FILE *fopen (char *filename, char *type);

filename:文件路径

type:打开文件的方式(有r、w、r+、w+、a、rb、wb等等)

用于判断文件是否存在可以使用 r 或者 rb ,因为使用 其它方式的话,可能会自动建立文件。 返回值为NULL(打不开)和正数(能打开)。

特别提醒:用这种方法做出的判断是不完全正确的,因为有的文件存在,但是可能不可读。

2.删除文件夹

RemoveDirectory()

调用Windows API函数 RemoveDirectory() ;但是只能删除空文件夹;对于非空文件夹无效

#include<windows.h>    //头文件  
#include<iostream>  
using namespace std;  
int main()  
{  
    string dirName = "D:\\test";    
    bool flag = RemoveDirectory(dirName.c_str());    
    return 0;  
}  
system()命令

system("rd D:\\test");

这个也只能删除空文件;如果想要删除非空文件夹可以使用

system("rd \s \q D:\\test");

\s强制

\q 安静模式,不提醒

3.获取文件夹下所有文件名

void getFiles(string path, vector<string>& files)
{
    //文件句柄
    long   hFile = 0;
    //文件信息
    struct _finddata_t fileinfo;
    string p;
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            //如果是目录,迭代之
            //如果不是,加入列表
            if ((fileinfo.attrib &  _A_SUBDIR))
            {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
            }
            else
            {
                files.push_back(p.assign(path).append("\\").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

4.读取以tab为分隔符的txt文件

此部分是在读取一个数据库文本文件学习的,每一个数据项大概有20个数据内容,最开始是以fscanf读入的,但是发现有的数据单元中是有空格的,fscanf会将数据截断。因而使用以字符方式读取,遇见’\t’则结束一个数据单元的读取。

#include <stdio.h>
#include <stdlib.h>
FILE *fin;
void main()
{
    char str[100];
    int c;
    int i=0;
    fin = fopen("a.dat","r"); // 打开文件,假定文件名是 a.dat
    while (1)
    {
        if (feof(fin)) { str[i]='\0'; printf("%s\n",str); break; }; // 如果读到文件尾
        c = fgetc(fin); // 读文件,读一个字符
        if (c=='\t') {str[i]='\0'; printf("%s\n",str); i=0;} // 如果是 tab键
        else { str[i]=c; i++;};
    }
fclose(fin); // 关文件
}

5.fscanf() fprintf()

fscanf()

从文件指针fp指向的文件中,按format中对应的控制格式读取数据,并存储在agars对应的变量中;

原型: fscanf(FILE *fp, const char *format, agars)

1.如果要读取一个整数(该整数必须在所存变量的数据类型表示的范围之内)则为:fscanf(fp, “%d”, &ch),而此时ch应该定义为int;若读取的数据大于int所能表示的范围,则读取的数据屏幕显示为负数,即读取的数据发生越界,如果此时的ch依然为char型,则运行时报错(内存读写错误)。

2.如果要读取字符串,则ch应该定义为char型数组或指针(指针需分配空间),而不能将其定义为char型,否则也会报错(内存读写错误);

3.输出数据时的数据格式应该和读取数据时的控制格式相同,除非进行强制转换。

4.使用fscanf()时,其中的变量agars应该取其地址;

5.对于文件的操作,记得文件打开操作后要关闭。

对于fscanf()主要应用在按行读取一个文件中的所有内容或依次读取每行相隔的几个数据,具体参照以下示例:

#include<stdio.h>
#include<stdlib.h> 
int main()
{
    FILE *fp;
    char *ch, *ah;
    ch =(char *) malloc(sizeof(char) * 100);
    ah =(char *) malloc(sizeof(char) * 100);
    fp = fopen("test.txt","r");
    if(fp == NULL)
    {
         printf("Open filefailure!");
         exit(1);
    }
    else
    {
         while(!feof(fp))
        {
             fscanf(fp, “%s”, ch);
             printf(“%s”, ch);//这两行为按行读取所有数据
             fscanf(fp, “%s%s”, ch, ah);
             printf(“The value of ch and ah is:%s %s\n”,ch,ah);//这两行为分别读取每行相隔的几个数据 
        }
    } 
    printf("%s\n",ch);
    free(ch);
    free(ah);
    fclose(fp);
    return 0;
} 
fprintf

将agars(参数表)内各项的值,按format(格式控制字符串)所表示的格式,将数据格式为字符串的形式写入到文件指针fp指向的文件中。

原型:fprintf(FILE *fp, const char *format, agars)

fprintf()和fscanf()相对应,其用法也基本和fscanf()相同。具体参照以下示例:

#include<stdio.h>
#include<stdlib.h> 
int main()
{
    FILE *fp;
    fp = fopen("test.txt","a+");
    fprintf(fp,“%d %d”,123456,789);//将123456和789写到test.txt文件中
    fprintf(fp,"%s %s","China","ChongQing"); //将字符串China和ChongQing追加写到test.txt文件中
    fclose(fp); 
    return 0;
}

文件中读写结构体

不建议使用一般的存储方式,而应该采取二进制读写,这样会方便读写操作,尤其是读取操作。

class Goods
{
protected:
    char goods_name[50]; //商品名称
    int goods_number; //商品代码
    char person_name[30]; //经办人
    int price; //进货价
    int amount; //库存量
    Goods *next;//定义指向类Goods的指针变量next
public:
    Goods(int goods_number=0,char*goods_name="null",char*person_name="null",int price=0,int amount=0)//定义构造函数
    {
        this->goods_number=goods_number;
        strcpy(this->goods_name,goods_name);
        strcpy(this->person_name,person_name);
        this->price=price;
        this->amount=amount;
    }
    void ShowData()//定义输出函数
    {
        cout<<"goods_number:"<<goods_number<<" goods_name:"<<goods_name<<" person_name:"<<person_name<<" price:"<<price<<" amount:"<<amount<<endl;
    }
};
int main () 
{
    //将结构体成员写入文件
    ofstream out("data.txt",ios::app|ios::binary);
    Goods x(1,"name1","das",1,1);
    Goods y(2,"name2","das2",2,2);
    Goods z(3,"name3","das3",3,3);
    if (out.is_open()) 
    {
        out.write((char*)&x,sizeof(x));
        out.write((char*)&y,sizeof(y));
        out.write((char*)&z,sizeof(z));
    }
   //从文件中以结构体为单元读取数据内容 
   Goods x,y,z;
   ifstream in("data.txt",ios::binary);  
   if (! in.is_open())  
   { 
       cout << "Error opening file";
       exit (1); 
   }
   while (!in.eof() )
   {  
       in.read((char*)&x,sizeof(x));
       in.read((char*)&y,sizeof(y));
       in.read((char*)&z,sizeof(z));
   }
   x.ShowData();
   y.ShowData();
   z.ShowData();

    return 0;
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值