64,678
社区成员
发帖
与我相关
我的任务
分享
int write_profile_string( const char *section, const char *key,const char *value, const char *file);//section 项(参数的所在项)//key参数名//value数据内容//file文件路径
int write_profile_string(const char *section, const char *key,
const char *value, const char *file)
{
char buf[MAX_FILE_SIZE]={0};
char w_buf[MAX_FILE_SIZE]={0};
int sec_s,sec_e,key_s,key_e, value_s, value_e;
int value_len = (int)strlen(value);
int file_size;
FILE *out;
//check parameters
assert(section != NULL && strlen(section));
assert(key != NULL && strlen(key));
assert(value != NULL);
assert(file !=NULL &&strlen(key));
if(!load_ini_file(file,buf,&file_size))
{
sec_s = -1;
}
else
{
parse_file(section,key,buf,&sec_s,&sec_e,&key_s,&key_e,&value_s,&value_e);
}
if( -1 == sec_s)
{
if(0==file_size)
{
sprintf(w_buf+file_size,"[%s]\n%s=%s\n",section,key,value);
}
else
{
//not find the section, then add the new section at end of the file
memcpy(w_buf,buf,file_size);
sprintf(w_buf+file_size,"\n[%s]\n%s=%s\n",section,key,value);
}
}
else if(-1 == key_s)
{
//not find the key, then add the new key=value at end of the section
memcpy(w_buf,buf,sec_e);
sprintf(w_buf+sec_e,"%s=%s\n",key,value);
sprintf(w_buf+sec_e+strlen(key)+strlen(value)+2,buf+sec_e, file_size - sec_e);
}
else
{
//update value with new value
memcpy(w_buf,buf,value_s);
memcpy(w_buf+value_s,value, value_len);
memcpy(w_buf+value_s+value_len, buf+value_e, file_size - value_e);
}
out = fopen(file,"w");
if(NULL == out)
{
return 0;
}
if(-1 == fputs(w_buf,out) )
{
fclose(out);
return 0;
}
fclose(out);
return 1;
}
这是个写参数的基础类。可以修改指定的参数数据。//问题:
// 1.打开一个文本文件。
// 2.查找这个文本文件的第r行的第c1-c2列?
//
// 如:
// 文件:a
// 11111111
// 22222QQQ
// 33333333
//
// 查找第2行,第6-8列。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXC 16000
char ln[MAXC];
FILE *f;
int r,c1,c2,n,L;
void getc1c2(char *fn) {
ln[c2]=0;
printf("Text at row(%d),column(%d..%d) of file %s is [%s]\n",r,c1,c2,fn,ln+c1-1);
}
int main(int argc,char **argv) {
if (argc<5) {
HELP:
printf("Usage:\n %s filename.ext r c1 c2\nto get text at row(r),column(c1..c2) of filename.ext\n",argv[0]);
return 1;
}
r=atoi(argv[2]);
c1=atoi(argv[3]);
c2=atoi(argv[4]);
if (r<=0 || c1<=0 || c2<c1 || c2>=MAXC) goto HELP;
f=fopen(argv[1],"r");
if (NULL==f) {
printf("Can not open file %s!\n",argv[1]);
return 2;
}
n=0;
while (1) {
if (NULL==fgets(ln,MAXC,f)) break;
L=strlen(ln);
if ('\n'==ln[L-1]) {
memset(ln+L-1,0,MAXC-L+1);
n++;
if (r==n) {getc1c2(argv[1]);break;}
} else {
n++;
if (r==n) {getc1c2(argv[1]);break;}
printf("Warning: line %d too long(>%d characters)! Ignore tails.",n,MAXC);
while (1) {
if (NULL==fgets(ln,MAXC,f)) goto END;
L=strlen(ln);
if ('\n'==ln[L-1]) break;
}
}
}
END:
fclose(f);
return 0;
}
//C:\test\Debug>frcc a 2 6 8
//Text at row(2),column(6..8) of file a is [QQQ]
//