freebsd下mysql清华包安装地址:
晓谦-水能载舟,亦能煮粥 说:
http://ftp2.tsinghua.edu.cn/pub/mirror/FreeBSD/ports/i386/packages-5-stable/databases/mysql-server-4.0.26.tbz
晓谦-水能载舟,亦能煮粥 说:
http://ftp2.tsinghua.edu.cn/pub/mirror/FreeBSD/ports/i386/packages-5-stable/databases/mysql-client-4.0.26.tbz
xdy108@126.com 说:
晓谦-水能载舟,亦能煮粥 说:
http://ftp2.tsinghua.edu.cn/pub/mirror/FreeBSD/ports/i386/packages-5-stable/databases/mysql-server-4.0.26.tbz
晓谦-水能载舟,亦能煮粥 说:
http://ftp2.tsinghua.edu.cn/pub/mirror/FreeBSD/ports/i386/packages-5-stable/databases/mysql-client-4.0.26.tbz
xdy108@126.com 说:
【URL:来源】http://bbs.linuxpk.com/thread-9632-1-1.html
我们如何查看错误信息呢?在哪里查看呢?应该到/usr/local/mysql/var目录中去找一个带有.err后缀的文件;
[root@bugkill var]# cd /usr/local/myql/var
[root@bugkill var]# more *.err
可能会出现存在下面的错误信息:
031203 14:49:10 mysqld started
031203 14:49:10 Can't start server : Bind on unix socket: Permission denied
031203 14:49:10 Do you already have another mysqld server running on socket: /tmp/mysql.sock ?
031203 14:49:10 Aborting
031203 14:49:10 /usr/local/mysql/libexec/mysqld: Shutdown Complete
031203 14:49:10 mysqld ended
其实这是权限方面的事,我们把权限设置一下就OK了。我们要设置的权限是/usr/local/mysql/var的目录。要设置为777。
方法是:
[root@bugkill mysql-4.1.9]# chmod 755 /usr/local/mysql/var
另外我们要用beinan这个用户来启动mysqld服务器,当然也得改变一下 /usr/local/mysql/var的属性
[root@bugkill mysql-4.1.9]# chown -R bugkill:bugkill /usr/local/mysql/var
[root@bugkill mysql-4.1.9]# su bugkill
How do I fix the following error SQL/DB Error errcode 13 Can't create/write to file?
Problem: The MySQL variable tmpdir is set to a directory that cannot be written to when using PHP to access MySQL.
To verify this, enter MySQL at the command line and type show variables;
You'll get a long list and one of them will read: tmpdir = /somedir/ (whatever your setting is.)
Solution: Alter the tmpdir variable to point to a writable directory.
Steps:
Find the my.cnf file. On *nix systems this is usually in /etc/.
Once found, open this in a simple text editor and find the [mysqld] section.
Under this section, find the tmpdir line. If this line is commented (has a # at the start), delete the # and edit the line so that it reads: tmpdir = /writable/dir where /writable/dir is a directory to which you can write. Some use /tmp, or you might also try /home//.
Save the file.
Shutdown MySQL by typing mysqlshutdown -u -p shutdown.
Start MySQL by going to the MySQL directory and typing ./bin/safe_mysqld &. Usually the MySQL directory is in /usr/local or sometimes in /usr/ on Linux systems.
If none of this make sense and you have someone to administrate your system for you, show the above to them and they should be able to figure it out.
原文:
打开:/etc/my.cnf
tmpdir = /usr/local/mysql/var/tmp 去掉#号
socket = /usr/local/mysql/var/mysql.sock
指向的要有写权限,restart mysql OK!然后再重启mysql服务器。
我们如何查看错误信息呢?在哪里查看呢?应该到/usr/local/mysql/var目录中去找一个带有.err后缀的文件;
[root@bugkill var]# cd /usr/local/myql/var
[root@bugkill var]# more *.err
可能会出现存在下面的错误信息:
031203 14:49:10 mysqld started
031203 14:49:10 Can't start server : Bind on unix socket: Permission denied
031203 14:49:10 Do you already have another mysqld server running on socket: /tmp/mysql.sock ?
031203 14:49:10 Aborting
031203 14:49:10 /usr/local/mysql/libexec/mysqld: Shutdown Complete
031203 14:49:10 mysqld ended
其实这是权限方面的事,我们把权限设置一下就OK了。我们要设置的权限是/usr/local/mysql/var的目录。要设置为777。
方法是:
[root@bugkill mysql-4.1.9]# chmod 755 /usr/local/mysql/var
另外我们要用beinan这个用户来启动mysqld服务器,当然也得改变一下 /usr/local/mysql/var的属性
[root@bugkill mysql-4.1.9]# chown -R bugkill:bugkill /usr/local/mysql/var
[root@bugkill mysql-4.1.9]# su bugkill
How do I fix the following error SQL/DB Error errcode 13 Can't create/write to file?
Problem: The MySQL variable tmpdir is set to a directory that cannot be written to when using PHP to access MySQL.
To verify this, enter MySQL at the command line and type show variables;
You'll get a long list and one of them will read: tmpdir = /somedir/ (whatever your setting is.)
Solution: Alter the tmpdir variable to point to a writable directory.
Steps:
Find the my.cnf file. On *nix systems this is usually in /etc/.
Once found, open this in a simple text editor and find the [mysqld] section.
Under this section, find the tmpdir line. If this line is commented (has a # at the start), delete the # and edit the line so that it reads: tmpdir = /writable/dir where /writable/dir is a directory to which you can write. Some use /tmp, or you might also try /home//.
Save the file.
Shutdown MySQL by typing mysqlshutdown -u -p shutdown.
Start MySQL by going to the MySQL directory and typing ./bin/safe_mysqld &. Usually the MySQL directory is in /usr/local or sometimes in /usr/ on Linux systems.
If none of this make sense and you have someone to administrate your system for you, show the above to them and they should be able to figure it out.
原文:
打开:/etc/my.cnf
tmpdir = /usr/local/mysql/var/tmp 去掉#号
socket = /usr/local/mysql/var/mysql.sock
指向的要有写权限,restart mysql OK!然后再重启mysql服务器。
mysql低版本日期相加:
select opendate,openlong,INTERVAL openlong DAY + opendate from enter_status;
线上跑的sql:
select a.enterpriseid,b.name,a.opendate,a.openlong,INTERVAL a.openlong DAY + a.opendate as now from enter_status a,domain b where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+7 and a.enterpriseid=b.enterpriseid
-----------------------------------------------------------------------------------------------------------------
select b.enterpriseid from enter_status a,enterprise b where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+1 and a.enterpriseid=b.enterpriseid and b.expiration=0 and b.flag=2 limit 10;
状态为 b.expiration=1 b.flag=1 为过期,发提醒信件,但是还能正常收发信,但是正常企业0 2 也有过期的,是由于程序没有放置标志位!
mysql -uroot -p enterprise < in.txt > out.txt
准确的sql:
SELECT b.enterpriseid,c.name,opendate,openlong,ADDDATE(a.opendate,a.openlong) from enter_status a,enterprise b,domain c where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+1 and a.enterpriseid=b.enterpriseid and b.enterpriseid=c.enterpriseid and a.enterpriseid=c.enterpriseid limit 15
更准确:
select b.enterpriseid,c.name,a.opendate,a.openlong,ADDDATE(a.opendate,a.openlong) from enter_status a,enterprise b,domain c where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+1 and a.enterpriseid=b.enterpriseid and b.enterpriseid=c.enterpriseid and a.enterpriseid=c.enterpriseid and b.expiration=1 and b.flag=1 group by c.enterpriseid limit 15;
select a.enterpriseid,b.name,a.opendate,a.openlong,ADDDATE(a.opendate,a.openlong) from enter_status a,domain b where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+7 and a.enterpriseid=b.enterpriseid;
导入时候第4行可能有错:改为:
`check` tinyint(4) NOT NULL default '1'
select opendate,openlong,INTERVAL openlong DAY + opendate from enter_status;
线上跑的sql:
select a.enterpriseid,b.name,a.opendate,a.openlong,INTERVAL a.openlong DAY + a.opendate as now from enter_status a,domain b where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+7 and a.enterpriseid=b.enterpriseid
-----------------------------------------------------------------------------------------------------------------
select b.enterpriseid from enter_status a,enterprise b where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+1 and a.enterpriseid=b.enterpriseid and b.expiration=0 and b.flag=2 limit 10;
状态为 b.expiration=1 b.flag=1 为过期,发提醒信件,但是还能正常收发信,但是正常企业0 2 也有过期的,是由于程序没有放置标志位!
mysql -uroot -p enterprise < in.txt > out.txt
准确的sql:
SELECT b.enterpriseid,c.name,opendate,openlong,ADDDATE(a.opendate,a.openlong) from enter_status a,enterprise b,domain c where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+1 and a.enterpriseid=b.enterpriseid and b.enterpriseid=c.enterpriseid and a.enterpriseid=c.enterpriseid limit 15
更准确:
select b.enterpriseid,c.name,a.opendate,a.openlong,ADDDATE(a.opendate,a.openlong) from enter_status a,enterprise b,domain c where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+1 and a.enterpriseid=b.enterpriseid and b.enterpriseid=c.enterpriseid and a.enterpriseid=c.enterpriseid and b.expiration=1 and b.flag=1 group by c.enterpriseid limit 15;
select a.enterpriseid,b.name,a.opendate,a.openlong,ADDDATE(a.opendate,a.openlong) from enter_status a,domain b where TO_DAYS(NOW()) - TO_DAYS(a.opendate) > a.openlong+7 and a.enterpriseid=b.enterpriseid;
导入时候第4行可能有错:改为:
`check` tinyint(4) NOT NULL default '1'
http://sqlserver.chinahtml.com/2005/mysql-1127986918405.shtml
#include <stdio.h>
#include <time.h>
using namespace std;
int main(void)
{
time_t t;
struct tm *x;
time( &t );
x = localtime(&t);
printf("year=[%d]\n", x->tm_year+1900);
printf("month=[%d]\n", x->tm_mon+1);
printf("day=[%d]\n", x->tm_mday);
printf("hour=[%d]\n", x->tm_hour);
printf("min=[%d]\n", x->tm_min);
printf("sec=[%d]\n", x->tm_sec);
return 0;
}
#include <time.h>
using namespace std;
int main(void)
{
time_t t;
struct tm *x;
time( &t );
x = localtime(&t);
printf("year=[%d]\n", x->tm_year+1900);
printf("month=[%d]\n", x->tm_mon+1);
printf("day=[%d]\n", x->tm_mday);
printf("hour=[%d]\n", x->tm_hour);
printf("min=[%d]\n", x->tm_min);
printf("sec=[%d]\n", x->tm_sec);
return 0;
}
CVS基本命令
goldway 发表于 2006-8-17 13:56:00
1. 检出源代码操作(cvs checkout)
*
将项目工作库目录取到个人工作库:cvs checkout dirname
*
将项目工作库中某个文件取到本地个人工作库:cvs checkout filename
2. 将文件同步到最新的版本(cvs update)
开发人员每天开始工作前,请将项目工作库中的最新版本代码文件取到个人工作库中,养成"先同步,后修改"的习惯;
更新单个文件:cvs update file_name
更新目录:cvs update (不指定文件名,cvs将同步所有子目录下的文件)
注意:第一次导出文件以后,就不是通过cvs checkout来同步文件了,而是要进入刚才cvs checkout project_name导出的project_name目录下进行具体文件的版本同步(添加,修改,删除)操作。
3. 文件提交(cvs commit)
确认文件修改写入CVS库:cvs commit -m "注释内容" file_name;
建议每次文件提交都只修改一个文件,以避免多个文件以同样注释commit到CVS库里了;每次确认提交时,请认真填写修改注释,以帮助其他开发人员了解修改的原因;
4. 添加(cvs add)
添加某个目录操作:cvs add dir_name
添加某个文件操作:cvs add new_file;
然后确认添加文件并注释
cvs commit -m "write some comments here"
对于图片,Word文档等非纯文本的项目,需要使用cvs add -kb选项按2进制文件方式导入,否则有可能出现文件被破坏的情况;
cvs add -kb readme.doc
5. 删除文件(cvs rm)
将某个文件物理删除操作:cvs remove -f file_name
确认删除文件并注释cvs commit -m "why delete file"
查看修改历史(cvs log)
查看日志操作命令:
cvs log file_name
cvs log dirname
操作历史命令:cvs history file_name
查看版本操作:cvs status -v filename
查看当前文件不同版本的区别:
cvs diff file_name
cvs diff -c file_name 查看对照的输出
6. 更名
cvs里没有cvs move或cvs rename两个命令;
可先移动老命名文件:cvs remove old_file_name;
然后再增加新命名文件实现更名操作:cvs add new_file_name;
例:将文件tt.c改名为test.c,具体操作如下
mv tt.c test.c
cvs remove -f tt.c
cvs commit -m "remove for rename" tt.c
cvs add test.c
7. 导出不带CVS目录的源代码文件
每个开发目录下,CVS都创建了一个CVS/目录。里面有文件用于记录当前目录和CVS库之间的对应信息。项目发布的时候一般不希望把文件目录还带着含有 CVS信息的CVS目录导出,这个一次性的导出过程使用cvs export命令,不过export只能针对一个TAG或者日期导出;
cvs export -r release1 project_name;
cvs export -D 20021023 project_name
cvs export -D now project_name
8. 基线标识
多个文件各自版本号不一样,项目到一定阶段,可以给所有文件统一指定一个阶段里程碑版本号,方便以后按照这个阶段里程碑版本号导出项目,同时也是项目的多个分支开发的基础;
确认版本基线cvs tag release_1_0
开始一个新的版本基线;
cvs commit -r 2 标记所有文件开始进入2.0的开发
cvs update -j release_1_0_patch_1
goldway 发表于 2006-8-17 13:56:00
1. 检出源代码操作(cvs checkout)
*
将项目工作库目录取到个人工作库:cvs checkout dirname
*
将项目工作库中某个文件取到本地个人工作库:cvs checkout filename
2. 将文件同步到最新的版本(cvs update)
开发人员每天开始工作前,请将项目工作库中的最新版本代码文件取到个人工作库中,养成"先同步,后修改"的习惯;
更新单个文件:cvs update file_name
更新目录:cvs update (不指定文件名,cvs将同步所有子目录下的文件)
注意:第一次导出文件以后,就不是通过cvs checkout来同步文件了,而是要进入刚才cvs checkout project_name导出的project_name目录下进行具体文件的版本同步(添加,修改,删除)操作。
3. 文件提交(cvs commit)
确认文件修改写入CVS库:cvs commit -m "注释内容" file_name;
建议每次文件提交都只修改一个文件,以避免多个文件以同样注释commit到CVS库里了;每次确认提交时,请认真填写修改注释,以帮助其他开发人员了解修改的原因;
4. 添加(cvs add)
添加某个目录操作:cvs add dir_name
添加某个文件操作:cvs add new_file;
然后确认添加文件并注释
cvs commit -m "write some comments here"
对于图片,Word文档等非纯文本的项目,需要使用cvs add -kb选项按2进制文件方式导入,否则有可能出现文件被破坏的情况;
cvs add -kb readme.doc
5. 删除文件(cvs rm)
将某个文件物理删除操作:cvs remove -f file_name
确认删除文件并注释cvs commit -m "why delete file"
查看修改历史(cvs log)
查看日志操作命令:
cvs log file_name
cvs log dirname
操作历史命令:cvs history file_name
查看版本操作:cvs status -v filename
查看当前文件不同版本的区别:
cvs diff file_name
cvs diff -c file_name 查看对照的输出
6. 更名
cvs里没有cvs move或cvs rename两个命令;
可先移动老命名文件:cvs remove old_file_name;
然后再增加新命名文件实现更名操作:cvs add new_file_name;
例:将文件tt.c改名为test.c,具体操作如下
mv tt.c test.c
cvs remove -f tt.c
cvs commit -m "remove for rename" tt.c
cvs add test.c
7. 导出不带CVS目录的源代码文件
每个开发目录下,CVS都创建了一个CVS/目录。里面有文件用于记录当前目录和CVS库之间的对应信息。项目发布的时候一般不希望把文件目录还带着含有 CVS信息的CVS目录导出,这个一次性的导出过程使用cvs export命令,不过export只能针对一个TAG或者日期导出;
cvs export -r release1 project_name;
cvs export -D 20021023 project_name
cvs export -D now project_name
8. 基线标识
多个文件各自版本号不一样,项目到一定阶段,可以给所有文件统一指定一个阶段里程碑版本号,方便以后按照这个阶段里程碑版本号导出项目,同时也是项目的多个分支开发的基础;
确认版本基线cvs tag release_1_0
开始一个新的版本基线;
cvs commit -r 2 标记所有文件开始进入2.0的开发
cvs update -j release_1_0_patch_1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <strstream>
#include <fstream> //ifstream fin("ent_list");
#include "../../entadmin_g/src/enterpriseManager.hpp"
char file_path1[1024]="/tmp/ent_not_exit.log"; //enterprise.domain的数据库select语句成功日志
char file_path2[1024]="/tmp/ent_failed_modify.log"; //enterprise.domain的数据库select语句失败日志
char file_path3[1024]="/tmp/ent_successful.log"; //enterprisemail.domain数据库的update修改成功日志
char file_path4[1024]="/tmp/startent_not_exit.log"; //enterprisemail.domain数据库的update语句修改失败日志
char file_path5[1024]="/tmp/startent_failed_modify.log"; //enterprisemail.domain蕌pdate语句修改失败日志
char file_path6[1024]="/tmp/startent_successful.log.log"; //enterprisemail.domain蕌pdate语句修改失败日志
int opt_type = 0;
char opt_file[1024];
void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}
using namespace std;
int main(int argv,char * argc[])//main函数体
{
if(argv!=3)
{
cout << "_____________________请在ent_list文件放入企业ID_______________\n";
cout << "|然后请传入参数? (0,1) |\n";
cout << "|传入1:ent_dated_restet 0 后跟关闭企业ID的文件 |\n";
cout << "|传入0:ent_dated_restet 1 后跟打开企业的ID文件 \n";
cout << "|______________________________________________________________|\n";
cout << "|_你只要将要关闭或者打开的企业ID放到ent_list由1或者0来控制即可_|\n";
cout << "| Warn: 连续一行一个企业ID(domain.enterpriseid) \n";
cout << "|Example: scan_enterprise_dated 0 /tmp/open_enterprise.txt|\n";
cout << "|______________________________________________________________|\n";
return 0;
}
time_t t;
struct tm *x;
time( &t );
x = localtime(&t);
opt_type=atoi(argc[1]); //判断是关闭企业还是恢复企业
strcpy(opt_file,argc[2]); //传入的文本文件,读取企业ID
enterprise *_enterprise = new enterprise( );
string errMsg;
//读取文本
FILE* fp;
fp = fopen(opt_file,"r");
if ( 0==fp )
{ cout << "What you put the filename is not exist!\n ";
return 0;
}
fclose(fp);
ifstream fin(opt_file);
//读取结束
ofstream fout1(file_path1,ios_base::app);//enterprise.domain的数据库select语句成功日志
ofstream fout2(file_path2,ios_base::app);//enterprise.domain的数据库select语句失败日志
ofstream fout3(file_path3,ios_base::app);//enterprisemail.domain数据库的update修改成功日志
ofstream fout4(file_path4,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
ofstream fout5(file_path5,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
ofstream fout6(file_path6,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
string str;
while(getline(fin,str))
{
trim(str);//去掉读出的一行前后空格
char buffer[1024];
int str_to_int=atoi(str.c_str());
sprintf(buffer,"%d",str_to_int);
if(strcmp(str.c_str(),buffer)!=0)
{
cout <<str<<"Have contain special character in one line,please check...\n";
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" <<str <<"\tHave contain special character in one line,please check...\n";
continue;
}
memset(buffer,0,1024);//销毁临时变量
//判断是否是数字
if (!str.length())
{
printf("请检查一下你的./ent_list里面是否有空行...\n");
return 0;
}
enterprise _enterprise1;
string enterpriseID;
enterpriseID=str;
if ( !_enterprise1.getEnterpriseInfo( atoi( enterpriseID.c_str() ), errMsg ) )
{
cout <<errMsg;
fout1 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<< errMsg<<"\n";
delete _enterprise;
return 0;
}
if ( opt_type == 0 )
{
if ( !_enterprise->stopDomain( atoi( enterpriseID.c_str() ), errMsg ) )
{
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<< errMsg<<"\n";
delete _enterprise;
return 0;
}
fout3 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<<"禁用企业成功"<<"\n";
delete _enterprise;
return 0;
}
if ( opt_type == 1 )
{
if ( !_enterprise->startDomain( atoi( enterpriseID.c_str() ), errMsg ) )
{
fout5 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<< errMsg<<"\n";
delete _enterprise;
return 0;
}
fout6<< x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t" << errMsg<<"\n";
delete _enterprise;
return 0;
}
}
fin.close();
fout1.close();
fout2.close();
fout3.close();
fout4.close();
fout5.close();
fout6.close();
}
all: scan_enterprise_dated.cgi
scan_enterprise_dated.cgi:
g++ -o ./scan_enterprise_dated.cgi scan_enterprise_dated.cpp ../../db/rpcserver/common/bin/freebsd/rpcsql_g.a ../../entadmin_g/oldlib/libStrLib.a ../../db/rpcserver/qmail/bin/freebsd/ent_rpcserver_clnt.a ../../db/rpcserver/qmail/ini.o ../../entsystem/email/entaddress/bin/freebsd/ent_domain.o ../../entsystem/email/entaddress/bin/freebsd/ent_add_tool.o -L../../entadmin/lib/ -I../../entadmin/lib/
clean:
rm -Rf scan_enterprise_dated.cgi
#include <time.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <strstream>
#include <fstream> //ifstream fin("ent_list");
#include "../../entadmin_g/src/enterpriseManager.hpp"
char file_path1[1024]="/tmp/ent_not_exit.log"; //enterprise.domain的数据库select语句成功日志
char file_path2[1024]="/tmp/ent_failed_modify.log"; //enterprise.domain的数据库select语句失败日志
char file_path3[1024]="/tmp/ent_successful.log"; //enterprisemail.domain数据库的update修改成功日志
char file_path4[1024]="/tmp/startent_not_exit.log"; //enterprisemail.domain数据库的update语句修改失败日志
char file_path5[1024]="/tmp/startent_failed_modify.log"; //enterprisemail.domain蕌pdate语句修改失败日志
char file_path6[1024]="/tmp/startent_successful.log.log"; //enterprisemail.domain蕌pdate语句修改失败日志
int opt_type = 0;
char opt_file[1024];
void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}
using namespace std;
int main(int argv,char * argc[])//main函数体
{
if(argv!=3)
{
cout << "_____________________请在ent_list文件放入企业ID_______________\n";
cout << "|然后请传入参数? (0,1) |\n";
cout << "|传入1:ent_dated_restet 0 后跟关闭企业ID的文件 |\n";
cout << "|传入0:ent_dated_restet 1 后跟打开企业的ID文件 \n";
cout << "|______________________________________________________________|\n";
cout << "|_你只要将要关闭或者打开的企业ID放到ent_list由1或者0来控制即可_|\n";
cout << "| Warn: 连续一行一个企业ID(domain.enterpriseid) \n";
cout << "|Example: scan_enterprise_dated 0 /tmp/open_enterprise.txt|\n";
cout << "|______________________________________________________________|\n";
return 0;
}
time_t t;
struct tm *x;
time( &t );
x = localtime(&t);
opt_type=atoi(argc[1]); //判断是关闭企业还是恢复企业
strcpy(opt_file,argc[2]); //传入的文本文件,读取企业ID
enterprise *_enterprise = new enterprise( );
string errMsg;
//读取文本
FILE* fp;
fp = fopen(opt_file,"r");
if ( 0==fp )
{ cout << "What you put the filename is not exist!\n ";
return 0;
}
fclose(fp);
ifstream fin(opt_file);
//读取结束
ofstream fout1(file_path1,ios_base::app);//enterprise.domain的数据库select语句成功日志
ofstream fout2(file_path2,ios_base::app);//enterprise.domain的数据库select语句失败日志
ofstream fout3(file_path3,ios_base::app);//enterprisemail.domain数据库的update修改成功日志
ofstream fout4(file_path4,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
ofstream fout5(file_path5,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
ofstream fout6(file_path6,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
string str;
while(getline(fin,str))
{
trim(str);//去掉读出的一行前后空格
char buffer[1024];
int str_to_int=atoi(str.c_str());
sprintf(buffer,"%d",str_to_int);
if(strcmp(str.c_str(),buffer)!=0)
{
cout <<str<<"Have contain special character in one line,please check...\n";
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" <<str <<"\tHave contain special character in one line,please check...\n";
continue;
}
memset(buffer,0,1024);//销毁临时变量
//判断是否是数字
if (!str.length())
{
printf("请检查一下你的./ent_list里面是否有空行...\n");
return 0;
}
enterprise _enterprise1;
string enterpriseID;
enterpriseID=str;
if ( !_enterprise1.getEnterpriseInfo( atoi( enterpriseID.c_str() ), errMsg ) )
{
cout <<errMsg;
fout1 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<< errMsg<<"\n";
delete _enterprise;
return 0;
}
if ( opt_type == 0 )
{
if ( !_enterprise->stopDomain( atoi( enterpriseID.c_str() ), errMsg ) )
{
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<< errMsg<<"\n";
delete _enterprise;
return 0;
}
fout3 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<<"禁用企业成功"<<"\n";
delete _enterprise;
return 0;
}
if ( opt_type == 1 )
{
if ( !_enterprise->startDomain( atoi( enterpriseID.c_str() ), errMsg ) )
{
fout5 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t"<< errMsg<<"\n";
delete _enterprise;
return 0;
}
fout6<< x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<enterpriseID<<"\t" << errMsg<<"\n";
delete _enterprise;
return 0;
}
}
fin.close();
fout1.close();
fout2.close();
fout3.close();
fout4.close();
fout5.close();
fout6.close();
}
all: scan_enterprise_dated.cgi
scan_enterprise_dated.cgi:
g++ -o ./scan_enterprise_dated.cgi scan_enterprise_dated.cpp ../../db/rpcserver/common/bin/freebsd/rpcsql_g.a ../../entadmin_g/oldlib/libStrLib.a ../../db/rpcserver/qmail/bin/freebsd/ent_rpcserver_clnt.a ../../db/rpcserver/qmail/ini.o ../../entsystem/email/entaddress/bin/freebsd/ent_domain.o ../../entsystem/email/entaddress/bin/freebsd/ent_add_tool.o -L../../entadmin/lib/ -I../../entadmin/lib/
clean:
rm -Rf scan_enterprise_dated.cgi
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <strstream>
#include <fstream> //ifstream fin("ent_list");
#include "/usr/local/mysql/include/mysql/mysql.h"
//const char mysqlServer[20] = "172.16.1.77";
const char mysqlServer[20] = "10.88.15.114";
const char user[20]="web";
const char password[20]="sinatest";
const char database[20]="enterprise";
const char database2[20]="enterprisemail";
unsigned int port=3306;
int flag=0;
char name[1024];
char query[1024];
char query2[1024];
char file_path[1024]="./ent_list"; //过期企业ID 数据文件
char file_path1[1024]="/tmp/enterprise.domain.successful.log"; //enterprise.domain的数据库select语句成功日志
char file_path2[1024]="/tmp/enterprise.domain.failed.log"; //enterprise.domain的数据库select语句失败日志
char file_path3[1024]="/tmp/enterprisemail.domain.successful.log"; //enterprisemail.domain数据库的update修改成功日志
char file_path4[1024]="/tmp/enterprisemail.domain.failed.log"; //enterprisemail.domain数据库的update语句修改失败日志
char file_path5[1024]="/tmp/enterprisemail.domain.successful.recover.log"; //enterprisemail.domain数据库的update语句修改失败日志
using namespace std;
//去掉读出的一行的前后空格
void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}
//去前后空格函数结束
int main(int argv,char * argc[])//main函数体
{
time_t t;
struct tm *x;
time( &t );
x = localtime(&t);
MYSQL myData,myData2,*sock,*sock2;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
mysql_init( &myData );
mysql_init( &myData2 );
if(argv!=2)
{
cout << "_____________________请在ent_list文件放入企业ID_______________\n";
cout << "|然后请传入参数? (1,0) |\n";
cout << "|传入1:ent_dated_restet 1 为打开过期续费企业 |\n";
cout << "|传入0:ent_dated_restet 0 关闭过期没有续费企业 \n";
cout << "|______________________________________________________________|\n";
cout << "|_你只要将要关闭或者打开的企业ID放到ent_list由1或者0来控制即可_|\n";
cout << "| Warn: 连续一行一个企业ID(domain.enterpriseid) \n";
cout << "|______________________________________________________________|\n";
return 0;
}
flag=atoi(argc[1]); //判断是关闭企业还是恢复企业
if(!(sock = mysql_real_connect( &myData, mysqlServer, user, password, database,port,NULL,0)))
{
printf("can not connect mysql error...(enterprise.domain)\n");
return 0;
}
if(!(sock2 = mysql_real_connect( &myData2, mysqlServer, user, password, database2,port,NULL,0)))
{
printf("can not connect mysql error...(enterprisemail.domain)\n");
return 0;
}
//读取文本
ifstream fin(file_path);
ofstream fout1(file_path1,ios_base::app);//enterprise.domain的数据库select语句成功日志
ofstream fout2(file_path2,ios_base::app);//enterprise.domain的数据库select语句失败日志
ofstream fout3(file_path3,ios_base::app);//enterprisemail.domain数据库的update修改成功日志
ofstream fout4(file_path4,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
ofstream fout5(file_path5,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
string str;
while(getline(fin,str))
{
trim(str);//去掉读出的一行前后空格
char buffer[1024];
int str_to_int=atoi(str.c_str());
sprintf(buffer,"%d",str_to_int);
if(strcmp(str.c_str(),buffer)!=0)
{
cout <<str<<"Have contain special character in one line,please check...\n";
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" <<str <<"\tHave contain special character in one line,please check...\n";
continue;
}
memset(buffer,0,1024);//销毁临时变量
//判断是否是数字
if (!str.length())
{
printf("请检查一下你的./ent_list里面是否有空行...\n");
return 0;
}
strcpy(query,"select name from `domain` where name not like \"%shenbak\" and enterpriseid=");
strcat(query,str.c_str());
cout<<query<<"\n";
if( mysql_query(&myData, query) != 0 )
{
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" <<str <<"\t Failed!\n"; //失败的select 查询记录到日志enterprise.domain.failed.log
continue;
}else{
res = mysql_store_result( &myData);
while(row = mysql_fetch_row(res))
{
fout1 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<"Enterpriseid:\t" << str <<"\tname:\t" << row[0] <<"\t Select sql Run Successful!\n";//写日志
strcpy(name,row[0]);
if(flag==0)
{
strcpy(query2,"update\t`domain` set name=replace(name,name,concat(name,\"shenbak\")) where name not like \"%shenbak\" and name=");
strcat(query2,"'");
strcat(query2,name);
strcat(query2,"'");
cout << query2<<"\n";
}
if(flag==1)
{
strcpy(query2,"update `domain` set name=replace(name,\"shenbak\",\"\") where name like \"%shenbak\" and name=");
strcat(query2,"'");
strcat(query2,name);
strcat(query2,"shenbak");
strcat(query2,"'");
}
if( mysql_query(&myData2, query2) != 0 )
{
fout4 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" << str <<"\tname:\t"<<name<<"\tupdate query failed!\n";
continue;
}else{
if(flag==0)
{
fout3 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<"Enterpriseid:\t" << str << "\tname:\t" <<name<<"\tupdate query successful!\n";
//写屏蔽日志
}
if(flag==1)
{
fout5 <<x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<"Enterpriseid:\t" << str << "\tname:\t" <<name<<"\tupdate query successful!\n";
//写日恢复日志
}
}
memset(name,0,1024);
}
str="";
memset(query,0,1024);
memset(query2,0,1024);
}
}
mysql_free_result(res);
mysql_close(&myData);
mysql_close(&myData2);
fin.close();
fout1.close();
fout2.close();
fout3.close();
fout4.close();
fout4.close();
cout << "\nAll task run ok....Goodbye!\n";
}
#include <time.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <strstream>
#include <fstream> //ifstream fin("ent_list");
#include "/usr/local/mysql/include/mysql/mysql.h"
//const char mysqlServer[20] = "172.16.1.77";
const char mysqlServer[20] = "10.88.15.114";
const char user[20]="web";
const char password[20]="sinatest";
const char database[20]="enterprise";
const char database2[20]="enterprisemail";
unsigned int port=3306;
int flag=0;
char name[1024];
char query[1024];
char query2[1024];
char file_path[1024]="./ent_list"; //过期企业ID 数据文件
char file_path1[1024]="/tmp/enterprise.domain.successful.log"; //enterprise.domain的数据库select语句成功日志
char file_path2[1024]="/tmp/enterprise.domain.failed.log"; //enterprise.domain的数据库select语句失败日志
char file_path3[1024]="/tmp/enterprisemail.domain.successful.log"; //enterprisemail.domain数据库的update修改成功日志
char file_path4[1024]="/tmp/enterprisemail.domain.failed.log"; //enterprisemail.domain数据库的update语句修改失败日志
char file_path5[1024]="/tmp/enterprisemail.domain.successful.recover.log"; //enterprisemail.domain数据库的update语句修改失败日志
using namespace std;
//去掉读出的一行的前后空格
void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}
//去前后空格函数结束
int main(int argv,char * argc[])//main函数体
{
time_t t;
struct tm *x;
time( &t );
x = localtime(&t);
MYSQL myData,myData2,*sock,*sock2;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
mysql_init( &myData );
mysql_init( &myData2 );
if(argv!=2)
{
cout << "_____________________请在ent_list文件放入企业ID_______________\n";
cout << "|然后请传入参数? (1,0) |\n";
cout << "|传入1:ent_dated_restet 1 为打开过期续费企业 |\n";
cout << "|传入0:ent_dated_restet 0 关闭过期没有续费企业 \n";
cout << "|______________________________________________________________|\n";
cout << "|_你只要将要关闭或者打开的企业ID放到ent_list由1或者0来控制即可_|\n";
cout << "| Warn: 连续一行一个企业ID(domain.enterpriseid) \n";
cout << "|______________________________________________________________|\n";
return 0;
}
flag=atoi(argc[1]); //判断是关闭企业还是恢复企业
if(!(sock = mysql_real_connect( &myData, mysqlServer, user, password, database,port,NULL,0)))
{
printf("can not connect mysql error...(enterprise.domain)\n");
return 0;
}
if(!(sock2 = mysql_real_connect( &myData2, mysqlServer, user, password, database2,port,NULL,0)))
{
printf("can not connect mysql error...(enterprisemail.domain)\n");
return 0;
}
//读取文本
ifstream fin(file_path);
ofstream fout1(file_path1,ios_base::app);//enterprise.domain的数据库select语句成功日志
ofstream fout2(file_path2,ios_base::app);//enterprise.domain的数据库select语句失败日志
ofstream fout3(file_path3,ios_base::app);//enterprisemail.domain数据库的update修改成功日志
ofstream fout4(file_path4,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
ofstream fout5(file_path5,ios_base::app); //enterprisemail.domain数据库的update语句修改失败日志
string str;
while(getline(fin,str))
{
trim(str);//去掉读出的一行前后空格
char buffer[1024];
int str_to_int=atoi(str.c_str());
sprintf(buffer,"%d",str_to_int);
if(strcmp(str.c_str(),buffer)!=0)
{
cout <<str<<"Have contain special character in one line,please check...\n";
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" <<str <<"\tHave contain special character in one line,please check...\n";
continue;
}
memset(buffer,0,1024);//销毁临时变量
//判断是否是数字
if (!str.length())
{
printf("请检查一下你的./ent_list里面是否有空行...\n");
return 0;
}
strcpy(query,"select name from `domain` where name not like \"%shenbak\" and enterpriseid=");
strcat(query,str.c_str());
cout<<query<<"\n";
if( mysql_query(&myData, query) != 0 )
{
fout2 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" <<str <<"\t Failed!\n"; //失败的select 查询记录到日志enterprise.domain.failed.log
continue;
}else{
res = mysql_store_result( &myData);
while(row = mysql_fetch_row(res))
{
fout1 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<"Enterpriseid:\t" << str <<"\tname:\t" << row[0] <<"\t Select sql Run Successful!\n";//写日志
strcpy(name,row[0]);
if(flag==0)
{
strcpy(query2,"update\t`domain` set name=replace(name,name,concat(name,\"shenbak\")) where name not like \"%shenbak\" and name=");
strcat(query2,"'");
strcat(query2,name);
strcat(query2,"'");
cout << query2<<"\n";
}
if(flag==1)
{
strcpy(query2,"update `domain` set name=replace(name,\"shenbak\",\"\") where name like \"%shenbak\" and name=");
strcat(query2,"'");
strcat(query2,name);
strcat(query2,"shenbak");
strcat(query2,"'");
}
if( mysql_query(&myData2, query2) != 0 )
{
fout4 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<< "Enterpriseid:\t" << str <<"\tname:\t"<<name<<"\tupdate query failed!\n";
continue;
}else{
if(flag==0)
{
fout3 << x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<"Enterpriseid:\t" << str << "\tname:\t" <<name<<"\tupdate query successful!\n";
//写屏蔽日志
}
if(flag==1)
{
fout5 <<x->tm_year+1900 <<"年"<<x->tm_mon+1<<"月"<<x->tm_mday<<"日"<<x->tm_hour<<"点"<<x->tm_min<<"分"<<x->tm_sec<<"秒\t"<<"Enterpriseid:\t" << str << "\tname:\t" <<name<<"\tupdate query successful!\n";
//写日恢复日志
}
}
memset(name,0,1024);
}
str="";
memset(query,0,1024);
memset(query2,0,1024);
}
}
mysql_free_result(res);
mysql_close(&myData);
mysql_close(&myData2);
fin.close();
fout1.close();
fout2.close();
fout3.close();
fout4.close();
fout4.close();
cout << "\nAll task run ok....Goodbye!\n";
}
http://www.mysql.com/doc/en/C.html
[转贴自http://homepage.qdcatv.com.cn/antonio/mysql/mysql.htm]
执行一个查询有以下几个步骤要做。首先执行一个查询,然后保存结果,
得到的是一个子集。这里是一个小例子:
#include
#include
#include "mysql.h"
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
void exiterr(int exitcode)
{
fprintf( stderr, "%s\n", mysql_error(&mysql) );
exit( exitcode );
}
int main()
{
uint i = 0;
if (!(mysql_connect(&mysql,"host","username","password")))
exiterr(1);
if (mysql_select_db(&mysql,"payroll"))
exiterr(2);
if (mysql_query(&mysql,"SELECT name,rate FROM emp_master"))
exiterr(3);
if (!(res = mysql_store_result(&mysql)))
exiterr(4);
while((row = mysql_fetch_row(res))) {
for (i=0 ; i < mysql_num_fields(res); i++)
printf("%s\n",row[i]);
}
mysql_free_result(res);
mysql_close(&mysql);
}
mysql_query 函数将把查询送给服务器,如果查询成功,调用mysql_store_result
函数将分配一个MYSQL_RES 结构并且重新从服务器获得一个结果集。你可以用
mysql_fetch_row 函数来查看数据。这样做你将获得一个 MYSQL_ROW 指针指向数
据中的一行。 MYSQL_ROW 指针是一简单的字符串数组。所有的数据类型被转换成
字符串送到客户端。
mysql_num_fields 函数将告诉你返回的列数。你可以继续调用 mysql_fetch_row
直到它返回一个空指针以得到查询中的每一行。
注意在这个例子里,我们没有检查有空指针的列。如果你不使用非空列的表,那么
你必须检查一个特殊行的列是否为空。
一旦你使用完毕一个结果集,你必须释放它。这通过 mysql_free_result 来完成。
最后调用 mysql_close 来关闭你和数据库之间的连接。
查看结果集
你可以不用调用 mysql_fetch_row 就查出返回的结果集共有多少行。这由
int mysql_num_rows(MYSQL_RES *result)来完成。
改变到被下一个 mysql_fetch_row 调用返回的行,你可以用
void mysql_data_seek(MYSQL_RES *res, uint offset) 改变到任意一行。
获得更多的信息
你可以使用这几个额外的函数来找出关于一个查询的更多的信息,并从服务器获得
这些信息。
如果你执行一个UPDATE, INSERT 或者 DELETE 查询,你可以用
int mysql_affected_rows 来查出共有多少行数据被你影响到。
如果在你的数据库里有二进制数据,那么得知数据的长度将是有用的。unsigned
int *mysql_fetch_lengths(MYSQL_RES *mysql) 将返回一指出了结果集中每一列
的长度的整型数组。
当你插入一个带有 AUTO_INCREMENT 列的表的时候,你可以用
int mysql_insert_id(MYSQL *mysql) 来查出生成的那一行的ID。
======================
我连过成功了!
#include "/include/mysql/mysql.h" /*为绝对路径*/
#include <stdio.h>
int main(int argc,char *argv[])
{
char *user = "root", *pwd = "mysql", *dbname = "mysql";
MYSQL mysql;
MYSQL_RES *mysql_ret;
MYSQL_ROW mysql_row;
unsigned long num_rows;
int ret;
mysql_init(&mysql);
if(mysql_real_connect(&mysql,NULL,user,pwd,dbname,0,NULL,0))
{
printf("Connection success!\n");
ret = mysql_query(&mysql,"select * from user");
if(!ret)
{
printf("Query Success!\n");
mysql_ret = mysql_store_result(&mysql);
if(mysql_ret != NULL)
{
printf("Store Result Success!\n");
num_rows = mysql_num_rows(mysql_ret);
if(num_rows != 0)
{
printf("%d\n",num_rows);
while(mysql_row = mysql_fetch_row(mysql_ret))
{
printf("%s\t%s\t%s\t%s\t%s\t%s\n",mysql_row[0],mysql_row[1],mysql_row[2],mysql_row[3],mysql_row[4],mysql_row[5]);
}
}
else
{
printf("mysql_num_rows Failed!\n");
exit(-1);
}
mysql_free_result(mysql_ret);
exit(0);
}
else
{
printf("Store Result Failed!\n");
exit(-1);
}
}
else
{
printf("Query Failed!\n");
exit(-1);
}
}
else
{
printf("Connection Failed\n");
exit(-1);
}
}
如果你包含了正确的头文件而在连接的时候, 告诉你没有符号连接
你应该连接你需要的库
我的/lib/mysql/libmysqlclient.so下面
gcc -L/lib/mysql -lmysqlclient -o tes tes.c 进行编译
RedHat_shu@hotmail.com
[转贴自http://homepage.qdcatv.com.cn/antonio/mysql/mysql.htm]
执行一个查询有以下几个步骤要做。首先执行一个查询,然后保存结果,
得到的是一个子集。这里是一个小例子:
#include
#include
#include "mysql.h"
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
void exiterr(int exitcode)
{
fprintf( stderr, "%s\n", mysql_error(&mysql) );
exit( exitcode );
}
int main()
{
uint i = 0;
if (!(mysql_connect(&mysql,"host","username","password")))
exiterr(1);
if (mysql_select_db(&mysql,"payroll"))
exiterr(2);
if (mysql_query(&mysql,"SELECT name,rate FROM emp_master"))
exiterr(3);
if (!(res = mysql_store_result(&mysql)))
exiterr(4);
while((row = mysql_fetch_row(res))) {
for (i=0 ; i < mysql_num_fields(res); i++)
printf("%s\n",row[i]);
}
mysql_free_result(res);
mysql_close(&mysql);
}
mysql_query 函数将把查询送给服务器,如果查询成功,调用mysql_store_result
函数将分配一个MYSQL_RES 结构并且重新从服务器获得一个结果集。你可以用
mysql_fetch_row 函数来查看数据。这样做你将获得一个 MYSQL_ROW 指针指向数
据中的一行。 MYSQL_ROW 指针是一简单的字符串数组。所有的数据类型被转换成
字符串送到客户端。
mysql_num_fields 函数将告诉你返回的列数。你可以继续调用 mysql_fetch_row
直到它返回一个空指针以得到查询中的每一行。
注意在这个例子里,我们没有检查有空指针的列。如果你不使用非空列的表,那么
你必须检查一个特殊行的列是否为空。
一旦你使用完毕一个结果集,你必须释放它。这通过 mysql_free_result 来完成。
最后调用 mysql_close 来关闭你和数据库之间的连接。
查看结果集
你可以不用调用 mysql_fetch_row 就查出返回的结果集共有多少行。这由
int mysql_num_rows(MYSQL_RES *result)来完成。
改变到被下一个 mysql_fetch_row 调用返回的行,你可以用
void mysql_data_seek(MYSQL_RES *res, uint offset) 改变到任意一行。
获得更多的信息
你可以使用这几个额外的函数来找出关于一个查询的更多的信息,并从服务器获得
这些信息。
如果你执行一个UPDATE, INSERT 或者 DELETE 查询,你可以用
int mysql_affected_rows 来查出共有多少行数据被你影响到。
如果在你的数据库里有二进制数据,那么得知数据的长度将是有用的。unsigned
int *mysql_fetch_lengths(MYSQL_RES *mysql) 将返回一指出了结果集中每一列
的长度的整型数组。
当你插入一个带有 AUTO_INCREMENT 列的表的时候,你可以用
int mysql_insert_id(MYSQL *mysql) 来查出生成的那一行的ID。
======================
我连过成功了!
#include "/include/mysql/mysql.h" /*为绝对路径*/
#include <stdio.h>
int main(int argc,char *argv[])
{
char *user = "root", *pwd = "mysql", *dbname = "mysql";
MYSQL mysql;
MYSQL_RES *mysql_ret;
MYSQL_ROW mysql_row;
unsigned long num_rows;
int ret;
mysql_init(&mysql);
if(mysql_real_connect(&mysql,NULL,user,pwd,dbname,0,NULL,0))
{
printf("Connection success!\n");
ret = mysql_query(&mysql,"select * from user");
if(!ret)
{
printf("Query Success!\n");
mysql_ret = mysql_store_result(&mysql);
if(mysql_ret != NULL)
{
printf("Store Result Success!\n");
num_rows = mysql_num_rows(mysql_ret);
if(num_rows != 0)
{
printf("%d\n",num_rows);
while(mysql_row = mysql_fetch_row(mysql_ret))
{
printf("%s\t%s\t%s\t%s\t%s\t%s\n",mysql_row[0],mysql_row[1],mysql_row[2],mysql_row[3],mysql_row[4],mysql_row[5]);
}
}
else
{
printf("mysql_num_rows Failed!\n");
exit(-1);
}
mysql_free_result(mysql_ret);
exit(0);
}
else
{
printf("Store Result Failed!\n");
exit(-1);
}
}
else
{
printf("Query Failed!\n");
exit(-1);
}
}
else
{
printf("Connection Failed\n");
exit(-1);
}
}
如果你包含了正确的头文件而在连接的时候, 告诉你没有符号连接
你应该连接你需要的库
我的/lib/mysql/libmysqlclient.so下面
gcc -L/lib/mysql -lmysqlclient -o tes tes.c 进行编译
RedHat_shu@hotmail.com
Simple Demo:
concat和Max混合用法:
select * from domain where enterpriseid='95358';
update `domain` set name=replace(name,name,concat(name,"shenbak")) where name not like "%shenbak" and enterpriseid='95358' ;
%表示后面有shenbak的,但是加了not,于是就没有问题了!
还回来:
update `domain` set name=replace(name,"shenbak","") where name like "%shenbak" and enterpriseid='95358';
update `film_info` set IMDB=REPLACE ( IMDB,'tt','');//将IMDB码的tt去掉,好建立索引
在数据转换的时候需要用到mysql的replace函数,这里简单介绍一下!
比如你要将 表 tb1里面的 f1字段的abc替换为def
Update tb1 SET f1=REPLACE(f1, 'abc', 'def');
REPLACE(str,from_str,to_str)
在字符串 str 中所有出现的字符串 from_str 均被 to_str替换,然后返回这个字符串:
mysql> Select REPLACE('www.mysql.com', 'w', 'Ww');
-> 'WwWwWw.mysql.com'
这个函数是多字节安全的。
示例:
Update `dede_addonarticle` SET body = REPLACE ( body,
'</td>',
'' );
Update `dede_addonarticle` SET body = REPLACE ( body,
'</tr>',
'' );
Update `dede_addonarticle` SET body = REPLACE ( body,
'<tr>',
'' );
Update `dede_archives` SET title= REPLACE ( title,
'大洋新闻 - ',
'' );
Update `dede_addonarticle` SET body = REPLACE ( body,
'../../../../../../',
'http://special.dayoo.com/meal/' );
mysql replace
用法1.replace intoreplace into table (id,name) values(‘1‘,‘aa‘),(‘2‘,‘bb‘)
此语句的作用是向表table中插入两条记录。
2.replace(object, search,replace)
把object中出现search的全部替换为replaceselect replace(‘www.163.com‘,‘w‘,‘Ww‘)--->WwW wWw.163.com
例:把表table中的name字段中的 aa替换为bbupdate table set name=replace(name,‘aa‘,‘bb‘)
本文转载自『北漂石头的博客』
http://www.niutian365.com/blog/
更多精彩内容,欢迎访问北漂石头的博客!
concat和Max混合用法:
select * from domain where enterpriseid='95358';
update `domain` set name=replace(name,name,concat(name,"shenbak")) where name not like "%shenbak" and enterpriseid='95358' ;
%表示后面有shenbak的,但是加了not,于是就没有问题了!
还回来:
update `domain` set name=replace(name,"shenbak","") where name like "%shenbak" and enterpriseid='95358';
update `film_info` set IMDB=REPLACE ( IMDB,'tt','');//将IMDB码的tt去掉,好建立索引
在数据转换的时候需要用到mysql的replace函数,这里简单介绍一下!
比如你要将 表 tb1里面的 f1字段的abc替换为def
Update tb1 SET f1=REPLACE(f1, 'abc', 'def');
REPLACE(str,from_str,to_str)
在字符串 str 中所有出现的字符串 from_str 均被 to_str替换,然后返回这个字符串:
mysql> Select REPLACE('www.mysql.com', 'w', 'Ww');
-> 'WwWwWw.mysql.com'
这个函数是多字节安全的。
示例:
Update `dede_addonarticle` SET body = REPLACE ( body,
'</td>',
'' );
Update `dede_addonarticle` SET body = REPLACE ( body,
'</tr>',
'' );
Update `dede_addonarticle` SET body = REPLACE ( body,
'<tr>',
'' );
Update `dede_archives` SET title= REPLACE ( title,
'大洋新闻 - ',
'' );
Update `dede_addonarticle` SET body = REPLACE ( body,
'../../../../../../',
'http://special.dayoo.com/meal/' );
mysql replace
用法1.replace intoreplace into table (id,name) values(‘1‘,‘aa‘),(‘2‘,‘bb‘)
此语句的作用是向表table中插入两条记录。
2.replace(object, search,replace)
把object中出现search的全部替换为replaceselect replace(‘www.163.com‘,‘w‘,‘Ww‘)--->WwW wWw.163.com
例:把表table中的name字段中的 aa替换为bbupdate table set name=replace(name,‘aa‘,‘bb‘)
本文转载自『北漂石头的博客』
http://www.niutian365.com/blog/
更多精彩内容,欢迎访问北漂石头的博客!
#include <string>
#include <iostream>
#include <strstream>
#include <fstream> //ifstream fin("ent_list");
#include "/usr/local/mysql/include/mysql/mysql.h"
const char mysqlServer[20] = "172.16.1.77";
//const char mysqlServer[20] = "10.88.15.114";
const char user[20]="web";
const char password[20]="sinatest";
const char database[20]="enterprise";
unsigned int port=3306;
using namespace std;
//去掉读出的一行的前后空格
void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}
//去前后空格函数结束
int main()//main函数体
{
MYSQL myData;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
int i,j,rowCount = 0,colCount = 0;
char query[1024];
mysql_init( &myData );
if(!mysql_real_connect( &myData, mysqlServer, user, password, database,port,NULL,0))
{
printf("connect mysql error!\n");
}
//读取文本
ifstream fin("ent_list");
string str;
while(getline(fin,str))
{
trim(str);//去掉读出的一行前后空格
//cout<<str<<"\n";
strcpy(query,"select path from enterprise where enterpriseid=");
strcat(query,str.c_str());
//fprintf(stderr,"FILE=%s,LINE=%d,query=%s\n",__FILE__,__LINE__,query);
if( mysql_query(&myData, query) != 0 )
{
printf("query error!\n");
return 0;
}else{
res = mysql_store_result( &myData );
rowCount = (int) mysql_num_rows( res );
colCount = (int) mysql_num_fields( res );
//printf(" result: %d records found\n fields: %d \n", rowCount, colCount);
row = mysql_fetch_row( res );
for(i = 0; i < rowCount; i++)
{
for( j = 0; j < colCount; j++)
{
cout <<"cd ";
printf("%s", row[j] );
cout <<";touch .expire;";
cout<<"\n";
}
}
}
}
}
#include <iostream>
#include <strstream>
#include <fstream> //ifstream fin("ent_list");
#include "/usr/local/mysql/include/mysql/mysql.h"
const char mysqlServer[20] = "172.16.1.77";
//const char mysqlServer[20] = "10.88.15.114";
const char user[20]="web";
const char password[20]="sinatest";
const char database[20]="enterprise";
unsigned int port=3306;
using namespace std;
//去掉读出的一行的前后空格
void trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
}
//去前后空格函数结束
int main()//main函数体
{
MYSQL myData;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
int i,j,rowCount = 0,colCount = 0;
char query[1024];
mysql_init( &myData );
if(!mysql_real_connect( &myData, mysqlServer, user, password, database,port,NULL,0))
{
printf("connect mysql error!\n");
}
//读取文本
ifstream fin("ent_list");
string str;
while(getline(fin,str))
{
trim(str);//去掉读出的一行前后空格
//cout<<str<<"\n";
strcpy(query,"select path from enterprise where enterpriseid=");
strcat(query,str.c_str());
//fprintf(stderr,"FILE=%s,LINE=%d,query=%s\n",__FILE__,__LINE__,query);
if( mysql_query(&myData, query) != 0 )
{
printf("query error!\n");
return 0;
}else{
res = mysql_store_result( &myData );
rowCount = (int) mysql_num_rows( res );
colCount = (int) mysql_num_fields( res );
//printf(" result: %d records found\n fields: %d \n", rowCount, colCount);
row = mysql_fetch_row( res );
for(i = 0; i < rowCount; i++)
{
for( j = 0; j < colCount; j++)
{
cout <<"cd ";
printf("%s", row[j] );
cout <<";touch .expire;";
cout<<"\n";
}
}
}
}
}
在该网站上注册一个帐号,就可以拥有该站提供的多台Solaris、Fedora等Unix/Linux服务器的登录帐号。对于想学习Unix/Linux系统,却又苦于没有合适的环境和条件的教师、学生和工程人员来说,这是一份不错的免费资源。
Unix体验中心:http://www.unix-center.net/
可以上传、下载文件的SSH客户端软件--SecureCRT:http://blog.s135.com/read.php/207.htm
以下简介信息摘自Unix体验中心:
Unix体验中心(Unix-Center.Net)的目标是为研究、学习和使用各种版本的Unix和类Unix操作系统的教师、学生和工程技术人员提供一个体验和测试各种版本的Unix和类Unix系统的软硬件平台。该平台能够为所有注册用户免费提供如下服务:
-- SSH登录
-- C/C++,Fortran,Java,Ruby,Python,Perl,Common Lisp等多种语言开发工具
本站的注册用户可以远程登录进入多个不同的系统,享受该系统上普通用户的所有权限,学习和使用各种版本的Unix和类Unix操作系统的常用命令和功能。开发人员更可以将自己正在开发的应用程序上载到Unix体验中心的服务器,在不同的软硬件平台上编译和运行,充分体验多处理器、多核、多线程的高性能计算的乐趣。
到目前为止,本站已经有五个系统正式投入使用,如下:
T1000/Solaris系统:
硬件环境:1 颗UltraSPARC T1芯片,CPU 主频为1.0 GHz,八核四线程配置8 GB内存
软件环境:Solaris 10 Update 3 for SPARC
机器域名:t1000.unix-center.net(公网),t1000-edu.unix-center.net(教育网)
X4100/Solaris系统:
硬件环境:2 颗双核单线程的AMD Opteron 280芯片,CPU 主频为2.4 GHz,配置4 GB内存
软件环境:Solaris 10 Update 3 for x86/x64
机器域名:x4100.unix-center.net(公网),x4100-edu.unix-center.net(教育网)
PE860/Solaris系统:
硬件环境:1 颗双核单线程的Intel Xeon 3050芯片,CPU 主频为2.13 GHz,配置1 GB内存
软件环境:Solaris 10 Update 3 for x86/x64
机器域名:solaris.unix-center.net(公网),solaris-edu.unix-center.net(教育网)
PE860/Fedora系统:
硬件环境:1 颗双核单线程的Intel Xeon 3050芯片,CPU 主频为2.13 GHz,配置1 GB内存
软件环境:Fedora Core 6
机器域名:fedora.unix-center.net(公网),fedora-edu.unix-center.net(教育网)
龙芯福珑系统:
硬件环境: 3 台配置龙芯2E处理器的龙芯福珑计算机,CPU 主频为666 MHz,配置256 MB内存
软件环境:Debian Linux for MIPS
机器域名:仅限内网连接
在2007年6 月底之前,本站还将增加一批新的服务器,届时将可以为网友提供FreeBSD和Ubuntu等多个版本的Unix和类Unix操作系统
Unix体验中心:http://www.unix-center.net/
可以上传、下载文件的SSH客户端软件--SecureCRT:http://blog.s135.com/read.php/207.htm
以下简介信息摘自Unix体验中心:
Unix体验中心(Unix-Center.Net)的目标是为研究、学习和使用各种版本的Unix和类Unix操作系统的教师、学生和工程技术人员提供一个体验和测试各种版本的Unix和类Unix系统的软硬件平台。该平台能够为所有注册用户免费提供如下服务:
-- SSH登录
-- C/C++,Fortran,Java,Ruby,Python,Perl,Common Lisp等多种语言开发工具
本站的注册用户可以远程登录进入多个不同的系统,享受该系统上普通用户的所有权限,学习和使用各种版本的Unix和类Unix操作系统的常用命令和功能。开发人员更可以将自己正在开发的应用程序上载到Unix体验中心的服务器,在不同的软硬件平台上编译和运行,充分体验多处理器、多核、多线程的高性能计算的乐趣。
到目前为止,本站已经有五个系统正式投入使用,如下:
T1000/Solaris系统:
硬件环境:1 颗UltraSPARC T1芯片,CPU 主频为1.0 GHz,八核四线程配置8 GB内存
软件环境:Solaris 10 Update 3 for SPARC
机器域名:t1000.unix-center.net(公网),t1000-edu.unix-center.net(教育网)
X4100/Solaris系统:
硬件环境:2 颗双核单线程的AMD Opteron 280芯片,CPU 主频为2.4 GHz,配置4 GB内存
软件环境:Solaris 10 Update 3 for x86/x64
机器域名:x4100.unix-center.net(公网),x4100-edu.unix-center.net(教育网)
PE860/Solaris系统:
硬件环境:1 颗双核单线程的Intel Xeon 3050芯片,CPU 主频为2.13 GHz,配置1 GB内存
软件环境:Solaris 10 Update 3 for x86/x64
机器域名:solaris.unix-center.net(公网),solaris-edu.unix-center.net(教育网)
PE860/Fedora系统:
硬件环境:1 颗双核单线程的Intel Xeon 3050芯片,CPU 主频为2.13 GHz,配置1 GB内存
软件环境:Fedora Core 6
机器域名:fedora.unix-center.net(公网),fedora-edu.unix-center.net(教育网)
龙芯福珑系统:
硬件环境: 3 台配置龙芯2E处理器的龙芯福珑计算机,CPU 主频为666 MHz,配置256 MB内存
软件环境:Debian Linux for MIPS
机器域名:仅限内网连接
在2007年6 月底之前,本站还将增加一批新的服务器,届时将可以为网友提供FreeBSD和Ubuntu等多个版本的Unix和类Unix操作系统
//该程序通过mysql数据库得到path,然后通过函数GetUserDetailFilename得到user_info?.conf ? 里面的数字,然后配合mysql数据库里面取得的内容写入到文本中,修复rpc造成的影响让webmail的企业通讯录下员工名录得以正常查看任何一个用户的详细信息!xiangdong2@staff.sina.com.cn
//测试enterpriseid=100334;
//CC -o user_info_mysql.cgi user_info_mysql.cpp -L/usr/local/lib/mysql -lmysqlclient -I/usr/local/include
#include <fstream>
#include <iostream>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <math.h>
#include "/usr/local/mysql/include/mysql/mysql.h"
const char mysqlServer[20] = "10.88.15.114";
const char user[20]="web";
const char password[20]="sinatest";
const char database[20]="enterprise";
unsigned int port=3306;
#define DETAILFILE_NUM 10
static int GetUserDetailFilename(const char *email, char *filename, const unsigned int size=1);
char path[1024];
char ent_address[21]="/ent_address/";
char filename[100];
char file_path_del[1024];
char buffer[1024],buffer1[1024],buffer2[1024],buffer3[1024],buffer4[1024],buffer5[1024],buffer6[1024],buffer7[1024],buffer8[1024],buffer9[1024];
using namespace std;
int main(int argc,char* argv[])
{
MYSQL myData;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
int i,j,rowCount = 0,colCount = 0;
string query="select path from enterprise where enterpriseid=";
string query2 = "select email,realname,tel,mobile,address,office,enter_time,num,dept,flag from enterprisemail_info where enterpriseid=";
if (argc < 2) {
printf("usage: 请输入enterprise库enterprise表里面企业id(enterpriseid? Such As:./user_info_mysql.cgi 100334)\n", argv[0]);
exit(1);
}
query+=argv[1];
query2+=argv[1];
mysql_init( &myData );
if(!mysql_real_connect( &myData, mysqlServer, user, password, database,port,NULL,0))
{
printf("connect mysql error!\n");
}
if( mysql_query(&myData, query.c_str()) != 0 )
{
printf("query error!\n");
return 0;
}else{
cout << "mysql query run ok!\n";
}
res = mysql_store_result( &myData );
row = mysql_fetch_row( res );
strcpy(path,row[0]);
//cout << row[0]<<path;取得path然后加入ent_address/
strcat(path,ent_address);
//cout << path<<"\n";
if( mysql_query(&myData, query2.c_str()) != 0 )
{
printf("query error!\n");
return 0;
}else{
cout << "mysql query run ok!\n";
}
res = mysql_store_result( &myData );
rowCount = (int) mysql_num_rows( res );
colCount = (int) mysql_num_fields( res );
//cout << "\t"<<colCount<<"\t"<<rowCount<<"\n";
char num[2];
for(i=0;i<=10;i++){//构造从user_info0.conf to user_info10.conf 路径然后del掉他们,为下面从数据库取写做准备
strcpy(file_path_del,path);
strcat(file_path_del,"user_info");
sprintf(num,"%d",i);
strcat(file_path_del,num);
strcat(file_path_del,".conf");
if( remove(file_path_del) != 0 )//删除文件
cout << "Error deleting "<< file_path_del <<" file, \t Because it is not exit! But it is still Ok...\n";
else
cout << "File" <<file_path_del<<" successfully deleted\n";
}
for(i = 0; i < rowCount; i++)
{
row = mysql_fetch_row( res );
for(j=0;j<colCount;j++){
strcpy(buffer,row[0]);
strcpy(buffer1,row[1]);
strcpy(buffer2,row[2]);
strcpy(buffer3,row[3]);
strcpy(buffer4,row[4]);
strcpy(buffer5,row[5]);
strcpy(buffer6,row[6]);
strcpy(buffer7,row[7]);
strcpy(buffer8,row[8]);
strcpy(buffer9,row[9]);
char* p = strstr(buffer,"@");
*p=0;
//取@前面的
const char *uid;
uid=buffer;
if(GetUserDetailFilename(uid, filename, 100)<0)//获取目录位置
{
cout<<"GetUserDetailFilename() erro...";
}
}//字段数循环
char file_path[1024];
strcpy(file_path,path);
strcat(file_path,filename);//得到文件的完整的path路径
//cout<<"file_path="<<file_path<<"\n\n";
//write file
ofstream fout(file_path,ios_base::app);
fout <<"[USER:"<<buffer<<"]\n"<<"EMAIL="<<buffer<<"\n"<<"REALNAME="<<buffer1<<"\n"<<"TEL="<<buffer2<<"\n"<<"MOBILE="<<buffer3<<"\n"<<"ADDRESS="<<buffer4<<"\n"<<"OFFICE="<<buffer5<<"\n"<<"ENTER_TIME="<<buffer6<<"\n"<<"NUM="<<buffer7<<"\n"<<"DEPT="<<buffer8<<"\n"<<"FLAG="<<buffer9<<"\n";
fout.close();
memset(file_path, 0, 1024);//清空该变量 清空其它字段缓存
memset(buffer, 0, 1024);
memset(buffer1, 0, 1024);
memset(buffer2, 0, 1024);
memset(buffer3, 0, 1024);
memset(buffer4, 0, 1024);
memset(buffer5, 0, 1024);
memset(buffer6, 0, 1024);
memset(buffer7, 0, 1024);
memset(buffer8, 0, 1024);
memset(buffer9, 0, 1024);
}//条目数
cout <<"\n\n\nVery good ,The task finished all right!\t goodbye...\n\n\n";
}
int GetUserDetailFilename(const char *email, char *filename, const unsigned
int size)
{
if(!email || !filename)return -1;
int t=0, n;
for(int i=0; i<strlen(email); i++)
t+=email[i];
n = (int)fmod(t, DETAILFILE_NUM)+1;
if(snprintf(filename, size, "user_info%d.conf", n)>=size)return -1;
return 0;
}
//测试enterpriseid=100334;
//CC -o user_info_mysql.cgi user_info_mysql.cpp -L/usr/local/lib/mysql -lmysqlclient -I/usr/local/include
#include <fstream>
#include <iostream>
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <math.h>
#include "/usr/local/mysql/include/mysql/mysql.h"
const char mysqlServer[20] = "10.88.15.114";
const char user[20]="web";
const char password[20]="sinatest";
const char database[20]="enterprise";
unsigned int port=3306;
#define DETAILFILE_NUM 10
static int GetUserDetailFilename(const char *email, char *filename, const unsigned int size=1);
char path[1024];
char ent_address[21]="/ent_address/";
char filename[100];
char file_path_del[1024];
char buffer[1024],buffer1[1024],buffer2[1024],buffer3[1024],buffer4[1024],buffer5[1024],buffer6[1024],buffer7[1024],buffer8[1024],buffer9[1024];
using namespace std;
int main(int argc,char* argv[])
{
MYSQL myData;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
int i,j,rowCount = 0,colCount = 0;
string query="select path from enterprise where enterpriseid=";
string query2 = "select email,realname,tel,mobile,address,office,enter_time,num,dept,flag from enterprisemail_info where enterpriseid=";
if (argc < 2) {
printf("usage: 请输入enterprise库enterprise表里面企业id(enterpriseid? Such As:./user_info_mysql.cgi 100334)\n", argv[0]);
exit(1);
}
query+=argv[1];
query2+=argv[1];
mysql_init( &myData );
if(!mysql_real_connect( &myData, mysqlServer, user, password, database,port,NULL,0))
{
printf("connect mysql error!\n");
}
if( mysql_query(&myData, query.c_str()) != 0 )
{
printf("query error!\n");
return 0;
}else{
cout << "mysql query run ok!\n";
}
res = mysql_store_result( &myData );
row = mysql_fetch_row( res );
strcpy(path,row[0]);
//cout << row[0]<<path;取得path然后加入ent_address/
strcat(path,ent_address);
//cout << path<<"\n";
if( mysql_query(&myData, query2.c_str()) != 0 )
{
printf("query error!\n");
return 0;
}else{
cout << "mysql query run ok!\n";
}
res = mysql_store_result( &myData );
rowCount = (int) mysql_num_rows( res );
colCount = (int) mysql_num_fields( res );
//cout << "\t"<<colCount<<"\t"<<rowCount<<"\n";
char num[2];
for(i=0;i<=10;i++){//构造从user_info0.conf to user_info10.conf 路径然后del掉他们,为下面从数据库取写做准备
strcpy(file_path_del,path);
strcat(file_path_del,"user_info");
sprintf(num,"%d",i);
strcat(file_path_del,num);
strcat(file_path_del,".conf");
if( remove(file_path_del) != 0 )//删除文件
cout << "Error deleting "<< file_path_del <<" file, \t Because it is not exit! But it is still Ok...\n";
else
cout << "File" <<file_path_del<<" successfully deleted\n";
}
for(i = 0; i < rowCount; i++)
{
row = mysql_fetch_row( res );
for(j=0;j<colCount;j++){
strcpy(buffer,row[0]);
strcpy(buffer1,row[1]);
strcpy(buffer2,row[2]);
strcpy(buffer3,row[3]);
strcpy(buffer4,row[4]);
strcpy(buffer5,row[5]);
strcpy(buffer6,row[6]);
strcpy(buffer7,row[7]);
strcpy(buffer8,row[8]);
strcpy(buffer9,row[9]);
char* p = strstr(buffer,"@");
*p=0;
//取@前面的
const char *uid;
uid=buffer;
if(GetUserDetailFilename(uid, filename, 100)<0)//获取目录位置
{
cout<<"GetUserDetailFilename() erro...";
}
}//字段数循环
char file_path[1024];
strcpy(file_path,path);
strcat(file_path,filename);//得到文件的完整的path路径
//cout<<"file_path="<<file_path<<"\n\n";
//write file
ofstream fout(file_path,ios_base::app);
fout <<"[USER:"<<buffer<<"]\n"<<"EMAIL="<<buffer<<"\n"<<"REALNAME="<<buffer1<<"\n"<<"TEL="<<buffer2<<"\n"<<"MOBILE="<<buffer3<<"\n"<<"ADDRESS="<<buffer4<<"\n"<<"OFFICE="<<buffer5<<"\n"<<"ENTER_TIME="<<buffer6<<"\n"<<"NUM="<<buffer7<<"\n"<<"DEPT="<<buffer8<<"\n"<<"FLAG="<<buffer9<<"\n";
fout.close();
memset(file_path, 0, 1024);//清空该变量 清空其它字段缓存
memset(buffer, 0, 1024);
memset(buffer1, 0, 1024);
memset(buffer2, 0, 1024);
memset(buffer3, 0, 1024);
memset(buffer4, 0, 1024);
memset(buffer5, 0, 1024);
memset(buffer6, 0, 1024);
memset(buffer7, 0, 1024);
memset(buffer8, 0, 1024);
memset(buffer9, 0, 1024);
}//条目数
cout <<"\n\n\nVery good ,The task finished all right!\t goodbye...\n\n\n";
}
int GetUserDetailFilename(const char *email, char *filename, const unsigned
int size)
{
if(!email || !filename)return -1;
int t=0, n;
for(int i=0; i<strlen(email); i++)
t+=email[i];
n = (int)fmod(t, DETAILFILE_NUM)+1;
if(snprintf(filename, size, "user_info%d.conf", n)>=size)return -1;
return 0;
}
remove function
int remove ( const char * filename ); <cstdio>
Remove file
Deletes the file whose name is specified in filename.
This is an operation performed directly on a file; No streams are involved in the operation.
Parameters
filename
C string containing the name of the file to be deleted. This paramenter must follow the file name specifications of the running environment and can include a path if the system supports it.
Return value
If the file is successfully deleted, a zero value is returned.
On failure, a nonzero value is reurned and the errno variable is set to the corresponding error code. Error codes are numerical values representing the type of failure occurred. A string interpreting this value can be printed to the standard error stream by a call to perror.
Example
/* remove example: remove myfile.txt */
#include <stdio.h>
int main ()
{
if( remove( "myfile.txt" ) != 0 )
perror( "Error deleting file" );
else
puts( "File successfully deleted" );
return 0;
}
If the file example.txt existed before the execution and we had write access to it, then the file will be deleted and this message will be written to stdout:
File successfully deleted
Otherwise, a message similar to this will be written to stderr:
Error deleting file: No such file or directory
See also
rename Rename file (function)
int remove ( const char * filename ); <cstdio>
Remove file
Deletes the file whose name is specified in filename.
This is an operation performed directly on a file; No streams are involved in the operation.
Parameters
filename
C string containing the name of the file to be deleted. This paramenter must follow the file name specifications of the running environment and can include a path if the system supports it.
Return value
If the file is successfully deleted, a zero value is returned.
On failure, a nonzero value is reurned and the errno variable is set to the corresponding error code. Error codes are numerical values representing the type of failure occurred. A string interpreting this value can be printed to the standard error stream by a call to perror.
Example
/* remove example: remove myfile.txt */
#include <stdio.h>
int main ()
{
if( remove( "myfile.txt" ) != 0 )
perror( "Error deleting file" );
else
puts( "File successfully deleted" );
return 0;
}
If the file example.txt existed before the execution and we had write access to it, then the file will be deleted and this message will be written to stdout:
File successfully deleted
Otherwise, a message similar to this will be written to stderr:
Error deleting file: No such file or directory
See also
rename Rename file (function)
问:
用PHP把数据库导出为excel文件,并且能导出格式及背景、线条等!
______________________________________________________________________________________________
答1:
gz
______________________________________________________________________________________________
答2:
gz
______________________________________________________________________________________________
答3:
如果是直接导出到EXCEL的话,依目前的技术能力似乎还不能做到。连大名鼎鼎的OpenOffice对EXCEL的支持也不是很好。
不过有种投机取巧的方法可以实现,就是从数据库中取出数据后,生成一个表格,样式自己定义好,然后让浏览器识别为下载excel。以下只是一个示例:
<?php
// 转载请注明phpteam
$title = "数据库名:test, 数据表:test, 备份日期:" . date("Y-m-d H:i:s");
$conn = @mysql_connect("localhost", "root", "") or die("不能连接数据库");
@mysql_select_db("test", $conn);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=test.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo '<table border="1" cellspacing="2" cellpadding="2" width="50%" align="center">';
// 输出标题
echo '<tr bgcolor="#cccccc"><td colspan="3" align="center">' . $title . '</td></tr>';
$query = "select * from test";
$result = mysql_query($query) or die(mysql_error());
$fields = mysql_num_fields($result);
// 输出字段名
echo '<tr bgcolor="blue">';
for($i = 0; $i < $fields; $i++) {
echo '<td>' . mysql_field_name($result, $i) . '</td>';
}
echo '</tr>';
// 输出内容
while($row = mysql_fetch_row($result)) {
echo '<tr>';
for($i = 0; $i<$fields; $i++) {
echo '<td>' . $row[$i] . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
______________________________________________________________________________________________
答4:
其实这个问题应该这样问:用ASP把数据库导出为excel文件,并且能导出格式及背景、线条等
如果行,则用php就行
______________________________________________________________________________________________
答5:
我今天找到一个网上,可以这样做的,但不知道怎么做的。
http://www.time-assistant.com/tastandard/hlogin.php
username:joesen
password:joesen
进入admin菜单下,有一个XLS按钮,导出为excel,导到本地,你看一下就知道了。
______________________________________________________________________________________________
答6:
哈哈,托你的福,我已经知道怎么解决了,你把下面着段代码存为.xls文件看看,知道该怎么做了吧?
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
<meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name></x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml><![endif]-->
</head>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td align="center" class="big6" >Users (except the ones disabled)</td></tr>
<tr><td class="greyborder">
<table border="1" align="center" width="100%" cellpadding="1" cellspacing="1">
<tr align="center">
<td class="TableTopHeader" nowrap>
Login </td>
<td class="TableTopHeader" nowrap>
Name </td>
<td class="TableTopHeader" width="3%" nowrap>
EMail </td>
<td class="TableTopHeader" nowrap>
Department </td>
<td class="TableTopHeader" nowrap>
Position </td>
<td class="TableTopHeader" nowrap width="1%">
Level </td>
<td class="TableTopHeader">Address</td>
<td class="TableTopHeader">Phone</td>
</tr>
<tr class="even">
<td class="mtlist"> joesen</td>
<td class="mtlist"> hong joesen</td>
<td class="mtlist" >allfu@163.net</td>
<td class="mtlist"> Software developments</td>
<td class="mtlist"> System Administrator</td>
<td class="mtlist"> Admin</td>
<td class="mtlist"> </td>
<td class="mtlist"> </td>
</tr>
</table>
</td></tr>
</table>
______________________________________________________________________________________________
答7:
结贴吧!
这就是 phpteam(我忍住不哭) 提供的方法
不错,不错。有长见识了!
______________________________________________________________________________________________
答8:
能说清楚点吗?我还是不明白。
______________________________________________________________________________________________
答9:
up
______________________________________________________________________________________________
答10:
zh_yuandc(中原大帝)贴出的就是从http://www.time-assistant.com/tastandard/hlogin.php
下载下来的.xls文件,你用文本编辑器打开就是那个样子。你用Excel打开就可以进行编辑。
我理解他是一个Excel可识别处理的xml文档,不是真正的Excel文档。但这已经很好了。
用PHP把数据库导出为excel文件,并且能导出格式及背景、线条等!
______________________________________________________________________________________________
答1:
gz
______________________________________________________________________________________________
答2:
gz
______________________________________________________________________________________________
答3:
如果是直接导出到EXCEL的话,依目前的技术能力似乎还不能做到。连大名鼎鼎的OpenOffice对EXCEL的支持也不是很好。
不过有种投机取巧的方法可以实现,就是从数据库中取出数据后,生成一个表格,样式自己定义好,然后让浏览器识别为下载excel。以下只是一个示例:
<?php
// 转载请注明phpteam
$title = "数据库名:test, 数据表:test, 备份日期:" . date("Y-m-d H:i:s");
$conn = @mysql_connect("localhost", "root", "") or die("不能连接数据库");
@mysql_select_db("test", $conn);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=test.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo '<table border="1" cellspacing="2" cellpadding="2" width="50%" align="center">';
// 输出标题
echo '<tr bgcolor="#cccccc"><td colspan="3" align="center">' . $title . '</td></tr>';
$query = "select * from test";
$result = mysql_query($query) or die(mysql_error());
$fields = mysql_num_fields($result);
// 输出字段名
echo '<tr bgcolor="blue">';
for($i = 0; $i < $fields; $i++) {
echo '<td>' . mysql_field_name($result, $i) . '</td>';
}
echo '</tr>';
// 输出内容
while($row = mysql_fetch_row($result)) {
echo '<tr>';
for($i = 0; $i<$fields; $i++) {
echo '<td>' . $row[$i] . '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
______________________________________________________________________________________________
答4:
其实这个问题应该这样问:用ASP把数据库导出为excel文件,并且能导出格式及背景、线条等
如果行,则用php就行
______________________________________________________________________________________________
答5:
我今天找到一个网上,可以这样做的,但不知道怎么做的。
http://www.time-assistant.com/tastandard/hlogin.php
username:joesen
password:joesen
进入admin菜单下,有一个XLS按钮,导出为excel,导到本地,你看一下就知道了。
______________________________________________________________________________________________
答6:
哈哈,托你的福,我已经知道怎么解决了,你把下面着段代码存为.xls文件看看,知道该怎么做了吧?
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">
<meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name></x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml><![endif]-->
</head>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td align="center" class="big6" >Users (except the ones disabled)</td></tr>
<tr><td class="greyborder">
<table border="1" align="center" width="100%" cellpadding="1" cellspacing="1">
<tr align="center">
<td class="TableTopHeader" nowrap>
Login </td>
<td class="TableTopHeader" nowrap>
Name </td>
<td class="TableTopHeader" width="3%" nowrap>
EMail </td>
<td class="TableTopHeader" nowrap>
Department </td>
<td class="TableTopHeader" nowrap>
Position </td>
<td class="TableTopHeader" nowrap width="1%">
Level </td>
<td class="TableTopHeader">Address</td>
<td class="TableTopHeader">Phone</td>
</tr>
<tr class="even">
<td class="mtlist"> joesen</td>
<td class="mtlist"> hong joesen</td>
<td class="mtlist" >allfu@163.net</td>
<td class="mtlist"> Software developments</td>
<td class="mtlist"> System Administrator</td>
<td class="mtlist"> Admin</td>
<td class="mtlist"> </td>
<td class="mtlist"> </td>
</tr>
</table>
</td></tr>
</table>
______________________________________________________________________________________________
答7:
结贴吧!
这就是 phpteam(我忍住不哭) 提供的方法
不错,不错。有长见识了!
______________________________________________________________________________________________
答8:
能说清楚点吗?我还是不明白。
______________________________________________________________________________________________
答9:
up
______________________________________________________________________________________________
答10:
zh_yuandc(中原大帝)贴出的就是从http://www.time-assistant.com/tastandard/hlogin.php
下载下来的.xls文件,你用文本编辑器打开就是那个样子。你用Excel打开就可以进行编辑。
我理解他是一个Excel可识别处理的xml文档,不是真正的Excel文档。但这已经很好了。
”文件”中如果没有指定路径,则在该可执行文件相同的文件夹下,如果指定路径则在该路径下,如:
ofstream ofile("output.dat");
ofstream ofile("c:\\temp\\output.dat");
如果文件不存在,则一般新建一个文件。打开方式,如按二进制打开
ofstream ofile("output.dat", ios_base::binary);
[b]如果追加方式打开,则:[/b]
ofstream ofile("output.dat", ios_base::app);
注意:ofstream 流在打开方式中已经默认了ios_base::out,故这个参数一般不必重复使用,如:
ofstream ofile("output.dat", ios_base::out);
早期的C++语言使用ios代替ios_base
序论
我曾发表过文件输入输出的文章,现在觉得有必要再写一点。文件 I/O 在C++中比烤蛋糕简单多了。 在这篇文章里,我会详细解释ASCII和二进制文件的输入输出的每个细节,值得注意的是,所有这些都是用C++完成的。
一、ASCII 输出
为了使用下面的方法, 你必须包含头文件<fstream.h>(译者注:在标准C++中,已经使用<fstream>取代< fstream.h>,所有的C++标准头文件都是无后缀的。)。这是 <iostream.h>的一个扩展集, 提供有缓冲的文件输入输出操作. 事实上, <iostream.h> 已经被<fstream.h>包含了, 所以你不必包含所有这两个文件, 如果你想显式包含他们,那随便你。我们从文件操作类的设计开始, 我会讲解如何进行ASCII I/O操作。如果你猜是"fstream," 恭喜你答对了! 但这篇文章介绍的方法,我们分别使用"ifstream"?和 "ofstream" 来作输入输出。
如果你用过标准控制台流"cin"?和 "cout," 那现在的事情对你来说很简单。 我们现在开始讲输出部分,首先声明一个类对象。
ofstream fout;
这就可以了,不过你要打开一个文件的话, 必须像这样调用ofstream::open()。
fout.open("output.txt");
你也可以把文件名作为构造参数来打开一个文件.
ofstream fout("output.txt");
这是我们使用的方法, 因为这样创建和打开一个文件看起来更简单. 顺便说一句, 如果你要打开的文件不存在,它会为你创建一个, 所以不用担心文件创建的问题. 现在就输出到文件,看起来和"cout"的操作很像。 对不了解控制台输出"cout"的人, 这里有个例子。
int num = 150;char name[] = "John Doe";fout << "Here is a number: " << num << "\n";fout << "Now here is a string: " << name << "\n";
现在保存文件,你必须关闭文件,或者回写文件缓冲. 文件关闭之后就不能再操作了, 所以只有在你不再操作这个文件的时候才调用它,它会自动保存文件。 回写缓冲区会在保持文件打开的情况下保存文件, 所以只要有必要就使用它。回写看起来像另一次输出, 然后调用方法关闭。像这样:
fout << flush; fout.close();
现在你用文本编辑器打开文件,内容看起来是这样:
Here is a number: 150 Now here is a string: John Doe
很简单吧! 现在继续文件输入, 需要一点技巧, 所以先确认你已经明白了流操作,对 "<<" 和">>" 比较熟悉了, 因为你接下来还要用到他们。继续…
二、ASCII 输入
输入和"cin" 流很像. 和刚刚讨论的输出流很像, 但你要考虑几件事情。在我们开始复杂的内容之前, 先看一个文本:
12 GameDev 15.45 L This is really awesome!
为了打开这个文件,你必须创建一个in-stream对象,?像这样。
ifstream fin("input.txt");
现在读入前四行. 你还记得怎么用"<<" 操作符往流里插入变量和符号吧?好,?在 "<<" (插入)?操作符之后,是">>" (提取) 操作符. 使用方法是一样的. 看这个代码片段.
int number; float real; char letter, word[8]; fin >> number; fin >> word; fin >> real; fin >> letter;
也可以把这四行读取文件的代码写为更简单的一行。
fin >> number >> word >> real >> letter;
它是如何运作的呢? 文件的每个空白之后, ">>" 操作符会停止读取内容, 直到遇到另一个>>操作符. 因为我们读取的每一行都被换行符分割开(是空白字符), ">>" 操作符只把这一行的内容读入变量。这就是这个代码也能正常工作的原因。但是,可别忘了文件的最后一行。
This is really awesome!
如果你想把整行读入一个char数组, 我们没办法用">>"?操作符,因为每个单词之间的空格(空白字符)会中止文件的读取。为了验证:
char sentence[101]; fin >> sentence;
我们想包含整个句子, "This is really awesome!" 但是因为空白, 现在它只包含了"This". 很明显, 肯定有读取整行的方法, 它就是getline()。这就是我们要做的。
fin.getline(sentence, 100);
这是函数参数. 第一个参数显然是用来接受的char数组. 第二个参数是在遇到换行符之前,数组允许接受的最大元素数量. 现在我们得到了想要的结果:“This is really awesome!”。
你应该已经知道如何读取和写入ASCII文件了。但我们还不能罢休,因为二进制文件还在等着我们。
三、二进制 输入输出
二进制文件会复杂一点, 但还是很简单的。 首先你要注意我们不再使用插入和提取操作符(译者注:<< 和 >> 操作符). 你可以这么做,但它不会用二进制方式读写。你必须使用read() 和write() 方法读取和写入二进制文件. 创建一个二进制文件, 看下一行。
ofstream fout("file.dat", ios::binary);
这会以二进制方式打开文件, 而不是默认的ASCII模式。首先从写入文件开始。函数write() 有两个参数。 第一个是指向对象的char类型的指针, 第二个是对象的大小(译者注:字节数)。 为了说明,看例子。
int number = 30; fout.write((char *)(&number), sizeof(number));
第一个参数写做"(char *)(&number)". 这是把一个整型变量转为char *指针。如果你不理解,可以立刻翻阅C++的书籍,如果有必要的话。第二个参数写作"sizeof(number)". sizeof() 返回对象大小的字节数. 就是这样!
二进制文件最好的地方是可以在一行把一个结构写入文件。 如果说,你的结构有12个不同的成员。 用ASCII?文件,你不得不每次一条的写入所有成员。 但二进制文件替你做好了。 看这个。
struct OBJECT { int number; char letter; } obj; obj.number = 15;obj.letter = ‘M’; fout.write((char *)(&obj), sizeof(obj));
这样就写入了整个结构! 接下来是输入. 输入也很简单,因为read()?函数的参数和 write()是完全一样的, 使用方法也相同。
ifstream fin("file.dat", ios::binary); fin.read((char *)(&obj), sizeof(obj));
我不多解释用法, 因为它和write()是完全相同的。二进制文件比ASCII文件简单, 但有个缺点是无法用文本编辑器编辑。 接着, 我解释一下ifstream 和ofstream 对象的其他一些方法作为结束.
四、更多方法
我已经解释了ASCII文件和二进制文件, 这里是一些没有提及的底层方法。
检查文件
你已经学会了open() 和close() 方法, 不过这里还有其它你可能用到的方法。
方法good() 返回一个布尔值,表示文件打开是否正确。
类似的,bad() 返回一个布尔值表示文件打开是否错误。 如果出错,就不要继续进一步的操作了。
最后一个检查的方法是fail(), 和bad()有点相似, 但没那么严重。
读文件
方法get() 每次返回一个字符。
方法ignore(int,char) 跳过一定数量的某个字符, 但你必须传给它两个参数。第一个是需要跳过的字符数。 第二个是一个字符, 当遇到的时候就会停止。 例子,
fin.ignore(100, ‘\n’);
会跳过100个字符,或者不足100的时候,跳过所有之前的字符,包括 ‘\n’。
方法peek() 返回文件中的下一个字符, 但并不实际读取它。所以如果你用peek() 查看下一个字符, 用get() 在peek()之后读取,会得到同一个字符, 然后移动文件计数器。
方法putback(char) 输入字符, 一次一个, 到流中。我没有见到过它的使用,但这个函数确实存在。
写文件
只有一个你可能会关注的方法.?那就是 put(char), 它每次向输出流中写入一个字符。
打开文件
当我们用这样的语法打开二进制文件:
ofstream fout("file.dat", ios::binary);
"ios::binary"是你提供的打开选项的额外标志. 默认的, 文件以ASCII方式打开, 不存在则创建, 存在就覆盖. 这里有些额外的标志用来改变选项。
ios::app 添加到文件尾
ios::ate 把文件标志放在末尾而非起始。
ios::trunc 默认. 截断并覆写文件。
ios::nocreate 文件不存在也不创建。
ios::noreplace 文件存在则失败。
文件状态
我用过的唯一一个状态函数是eof(), 它返回是否标志已经到了文件末尾。 我主要用在循环中。 例如, 这个代码断统计小写‘e’ 在文件中出现的次数。
ifstream fin("file.txt"); char ch; int counter; while (!fin.eof()) { ch = fin.get(); if (ch == ‘e’) counter++; }fin.close();
我从未用过这里没有提到的其他方法。 还有很多方法,但是他们很少被使用。参考C++书籍或者文件流的帮助文档来了解其他的方法。
结论
你应该已经掌握了如何使用ASCII文件和二进制文件。有很多方法可以帮你实现输入输出,尽管很少有人使用他们。我知道很多人不熟悉文件I/O操作,我希望这篇文章对你有所帮助。 每个人都应该知道. 文件I/O还有很多显而易见的方法,?例如包含文件 <stdio.h>. 我更喜欢用流是因为他们更简单。 祝所有读了这篇文章的人好运, 也许以后我还会为你们写些东西。
//使用(C++库)ofstream写文件数据
//simple example
#include <iostream>
#include <fstream>
using namespace std;
#ifdef WIN32
#define TEST_FILE "c:\\shi\\aaa.txt"
#else
#define TEST_FILE "/tmp/test.txt"
#endif
void test()
{
//ofstream ofs;
//ofs.open(TEST_FILE);
ofstream ofs(TEST_FILE);
char ch = '#';
const char buf[] = "1234567890";
ofs.put(ch);//simple
ofs.write(buf, sizeof(buf));
ofs.put(ch);
ofs.close();
}
int main(int argc, char* argv[])
{
test();
return 0;
}
ofstream ofile("output.dat");
ofstream ofile("c:\\temp\\output.dat");
如果文件不存在,则一般新建一个文件。打开方式,如按二进制打开
ofstream ofile("output.dat", ios_base::binary);
[b]如果追加方式打开,则:[/b]
ofstream ofile("output.dat", ios_base::app);
注意:ofstream 流在打开方式中已经默认了ios_base::out,故这个参数一般不必重复使用,如:
ofstream ofile("output.dat", ios_base::out);
早期的C++语言使用ios代替ios_base
序论
我曾发表过文件输入输出的文章,现在觉得有必要再写一点。文件 I/O 在C++中比烤蛋糕简单多了。 在这篇文章里,我会详细解释ASCII和二进制文件的输入输出的每个细节,值得注意的是,所有这些都是用C++完成的。
一、ASCII 输出
为了使用下面的方法, 你必须包含头文件<fstream.h>(译者注:在标准C++中,已经使用<fstream>取代< fstream.h>,所有的C++标准头文件都是无后缀的。)。这是 <iostream.h>的一个扩展集, 提供有缓冲的文件输入输出操作. 事实上, <iostream.h> 已经被<fstream.h>包含了, 所以你不必包含所有这两个文件, 如果你想显式包含他们,那随便你。我们从文件操作类的设计开始, 我会讲解如何进行ASCII I/O操作。如果你猜是"fstream," 恭喜你答对了! 但这篇文章介绍的方法,我们分别使用"ifstream"?和 "ofstream" 来作输入输出。
如果你用过标准控制台流"cin"?和 "cout," 那现在的事情对你来说很简单。 我们现在开始讲输出部分,首先声明一个类对象。
ofstream fout;
这就可以了,不过你要打开一个文件的话, 必须像这样调用ofstream::open()。
fout.open("output.txt");
你也可以把文件名作为构造参数来打开一个文件.
ofstream fout("output.txt");
这是我们使用的方法, 因为这样创建和打开一个文件看起来更简单. 顺便说一句, 如果你要打开的文件不存在,它会为你创建一个, 所以不用担心文件创建的问题. 现在就输出到文件,看起来和"cout"的操作很像。 对不了解控制台输出"cout"的人, 这里有个例子。
int num = 150;char name[] = "John Doe";fout << "Here is a number: " << num << "\n";fout << "Now here is a string: " << name << "\n";
现在保存文件,你必须关闭文件,或者回写文件缓冲. 文件关闭之后就不能再操作了, 所以只有在你不再操作这个文件的时候才调用它,它会自动保存文件。 回写缓冲区会在保持文件打开的情况下保存文件, 所以只要有必要就使用它。回写看起来像另一次输出, 然后调用方法关闭。像这样:
fout << flush; fout.close();
现在你用文本编辑器打开文件,内容看起来是这样:
Here is a number: 150 Now here is a string: John Doe
很简单吧! 现在继续文件输入, 需要一点技巧, 所以先确认你已经明白了流操作,对 "<<" 和">>" 比较熟悉了, 因为你接下来还要用到他们。继续…
二、ASCII 输入
输入和"cin" 流很像. 和刚刚讨论的输出流很像, 但你要考虑几件事情。在我们开始复杂的内容之前, 先看一个文本:
12 GameDev 15.45 L This is really awesome!
为了打开这个文件,你必须创建一个in-stream对象,?像这样。
ifstream fin("input.txt");
现在读入前四行. 你还记得怎么用"<<" 操作符往流里插入变量和符号吧?好,?在 "<<" (插入)?操作符之后,是">>" (提取) 操作符. 使用方法是一样的. 看这个代码片段.
int number; float real; char letter, word[8]; fin >> number; fin >> word; fin >> real; fin >> letter;
也可以把这四行读取文件的代码写为更简单的一行。
fin >> number >> word >> real >> letter;
它是如何运作的呢? 文件的每个空白之后, ">>" 操作符会停止读取内容, 直到遇到另一个>>操作符. 因为我们读取的每一行都被换行符分割开(是空白字符), ">>" 操作符只把这一行的内容读入变量。这就是这个代码也能正常工作的原因。但是,可别忘了文件的最后一行。
This is really awesome!
如果你想把整行读入一个char数组, 我们没办法用">>"?操作符,因为每个单词之间的空格(空白字符)会中止文件的读取。为了验证:
char sentence[101]; fin >> sentence;
我们想包含整个句子, "This is really awesome!" 但是因为空白, 现在它只包含了"This". 很明显, 肯定有读取整行的方法, 它就是getline()。这就是我们要做的。
fin.getline(sentence, 100);
这是函数参数. 第一个参数显然是用来接受的char数组. 第二个参数是在遇到换行符之前,数组允许接受的最大元素数量. 现在我们得到了想要的结果:“This is really awesome!”。
你应该已经知道如何读取和写入ASCII文件了。但我们还不能罢休,因为二进制文件还在等着我们。
三、二进制 输入输出
二进制文件会复杂一点, 但还是很简单的。 首先你要注意我们不再使用插入和提取操作符(译者注:<< 和 >> 操作符). 你可以这么做,但它不会用二进制方式读写。你必须使用read() 和write() 方法读取和写入二进制文件. 创建一个二进制文件, 看下一行。
ofstream fout("file.dat", ios::binary);
这会以二进制方式打开文件, 而不是默认的ASCII模式。首先从写入文件开始。函数write() 有两个参数。 第一个是指向对象的char类型的指针, 第二个是对象的大小(译者注:字节数)。 为了说明,看例子。
int number = 30; fout.write((char *)(&number), sizeof(number));
第一个参数写做"(char *)(&number)". 这是把一个整型变量转为char *指针。如果你不理解,可以立刻翻阅C++的书籍,如果有必要的话。第二个参数写作"sizeof(number)". sizeof() 返回对象大小的字节数. 就是这样!
二进制文件最好的地方是可以在一行把一个结构写入文件。 如果说,你的结构有12个不同的成员。 用ASCII?文件,你不得不每次一条的写入所有成员。 但二进制文件替你做好了。 看这个。
struct OBJECT { int number; char letter; } obj; obj.number = 15;obj.letter = ‘M’; fout.write((char *)(&obj), sizeof(obj));
这样就写入了整个结构! 接下来是输入. 输入也很简单,因为read()?函数的参数和 write()是完全一样的, 使用方法也相同。
ifstream fin("file.dat", ios::binary); fin.read((char *)(&obj), sizeof(obj));
我不多解释用法, 因为它和write()是完全相同的。二进制文件比ASCII文件简单, 但有个缺点是无法用文本编辑器编辑。 接着, 我解释一下ifstream 和ofstream 对象的其他一些方法作为结束.
四、更多方法
我已经解释了ASCII文件和二进制文件, 这里是一些没有提及的底层方法。
检查文件
你已经学会了open() 和close() 方法, 不过这里还有其它你可能用到的方法。
方法good() 返回一个布尔值,表示文件打开是否正确。
类似的,bad() 返回一个布尔值表示文件打开是否错误。 如果出错,就不要继续进一步的操作了。
最后一个检查的方法是fail(), 和bad()有点相似, 但没那么严重。
读文件
方法get() 每次返回一个字符。
方法ignore(int,char) 跳过一定数量的某个字符, 但你必须传给它两个参数。第一个是需要跳过的字符数。 第二个是一个字符, 当遇到的时候就会停止。 例子,
fin.ignore(100, ‘\n’);
会跳过100个字符,或者不足100的时候,跳过所有之前的字符,包括 ‘\n’。
方法peek() 返回文件中的下一个字符, 但并不实际读取它。所以如果你用peek() 查看下一个字符, 用get() 在peek()之后读取,会得到同一个字符, 然后移动文件计数器。
方法putback(char) 输入字符, 一次一个, 到流中。我没有见到过它的使用,但这个函数确实存在。
写文件
只有一个你可能会关注的方法.?那就是 put(char), 它每次向输出流中写入一个字符。
打开文件
当我们用这样的语法打开二进制文件:
ofstream fout("file.dat", ios::binary);
"ios::binary"是你提供的打开选项的额外标志. 默认的, 文件以ASCII方式打开, 不存在则创建, 存在就覆盖. 这里有些额外的标志用来改变选项。
ios::app 添加到文件尾
ios::ate 把文件标志放在末尾而非起始。
ios::trunc 默认. 截断并覆写文件。
ios::nocreate 文件不存在也不创建。
ios::noreplace 文件存在则失败。
文件状态
我用过的唯一一个状态函数是eof(), 它返回是否标志已经到了文件末尾。 我主要用在循环中。 例如, 这个代码断统计小写‘e’ 在文件中出现的次数。
ifstream fin("file.txt"); char ch; int counter; while (!fin.eof()) { ch = fin.get(); if (ch == ‘e’) counter++; }fin.close();
我从未用过这里没有提到的其他方法。 还有很多方法,但是他们很少被使用。参考C++书籍或者文件流的帮助文档来了解其他的方法。
结论
你应该已经掌握了如何使用ASCII文件和二进制文件。有很多方法可以帮你实现输入输出,尽管很少有人使用他们。我知道很多人不熟悉文件I/O操作,我希望这篇文章对你有所帮助。 每个人都应该知道. 文件I/O还有很多显而易见的方法,?例如包含文件 <stdio.h>. 我更喜欢用流是因为他们更简单。 祝所有读了这篇文章的人好运, 也许以后我还会为你们写些东西。
//使用(C++库)ofstream写文件数据
//simple example
#include <iostream>
#include <fstream>
using namespace std;
#ifdef WIN32
#define TEST_FILE "c:\\shi\\aaa.txt"
#else
#define TEST_FILE "/tmp/test.txt"
#endif
void test()
{
//ofstream ofs;
//ofs.open(TEST_FILE);
ofstream ofs(TEST_FILE);
char ch = '#';
const char buf[] = "1234567890";
ofs.put(ch);//simple
ofs.write(buf, sizeof(buf));
ofs.put(ch);
ofs.close();
}
int main(int argc, char* argv[])
{
test();
return 0;
}