fdopen

fopen()、fdopen()、close()
2010年01月03日 星期日 12:58

Linux环境下可以使用下列函数打开一个流,其函数原型如下:
#include <stdio.h>
FILE * fopen(const char * restrict pathname,
const char * restrict type);
FILE * fdopen(int filedes, const char *type);
fopen函数的第1个参数表示需要打开文件的路径,第2个参数type表示打开的方式,该值以一个字符串的形式传入,
type 字串中包含字母a的表示"追加写",即流打开以后,文件的读写位置在文件的末尾,所以成为追加写;type字串中包括字母b的表示流以二进制文件的形式打 开,其他的则表示流以文本文件的形式打开。这一点对于Linux系统来讲没有意义,因为Linux系统下的二进制文件和文本文件都是普通文件,是字节流, 内核并不区分这二者。
如果成功打开流,fopen函数返回一个FILE对象的指针,用户可以使用该指针操作这个流;如果失败则返回NULL,并且设置errno错误号。一般来讲,fopen函数是很少出错的,其原因主要有以下3种。
指定的文件路径有问题。type参数是一个非法字符串。文件的操作权限不够。
fdopen 函数用于在一个已经打开的文件描述符上打开一个流,其第1个参数表示一个已经打开的文件描述符,第2个参数type的意义和fopen函数的第2个参数一 样。只有一点不同的是,由于文件已经被打开,所以fdopen函数不会创建文件,而且也不会将文件截短为0,这一点要特别注意。这两步操作在打开该文件描 述符的时候已经完成。
Linux环境下使用fclose函数关闭一个流,其函数原型如下:
#include <stdio.h>
int fclose(FILE *fp);
fclose函数的参数是一个FILE对象的指针,它指向需要关闭的流。如果关闭成功,fclose函数返回0,失败返回EOF。这个值是一个定义在stdio.h文件中的宏,其值是-1。
下面实例演示了打开和关闭一个流。
(1)在vi编辑器中编辑该程序如下:
程序清单21-2 stream.c 打开并关闭一个流
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
FILE *fp;
int fd;
if( (fp = fopen("test.txt", "r+")) == NULL){ /* 以读写方式打开流 */
perror("fail to open");
exit(1);
}
fprintf(fp, "hello world/n"); /* 向该流输出一段信息,这段信息会反馈到文件上 */
fclose(fp);      /* 关闭流 */
if( (fd = open("test.txt", O_RDWR) == -1){ /* 以读写的方式打开文件 */
perror("fail to open");
exit(1);
}
if((fp = fdopen(fd, "r+") == NULL){ /* 在打开的文件上打开一个流 */
perror("fail to open stream");
exit(1);
}
fprintf("hello world again/n");
fclose(fp);     /* 关闭流,文件也被关闭 */
return 0;
}
(2)在shell中编译该程序如下:
$gcc stream.c -o stream
(3)在shell中运行该程序如下:
$./stream
(4)打开test.txt文件,可以见到文件内有以下信息。
$cat test.txt
hello world
hello world again

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
优化代码 def fault_classification_wrapper(vin, main_path, data_path, log_path, done_path): start_time = time.time() isc_path = os.path.join(done_path, vin, 'isc_cal_result', f'{vin}_report.xlsx') if not os.path.exists(isc_path): print('No isc detection input!') else: isc_input = isc_produce_alarm(isc_path, vin) ica_path = os.path.join(done_path, vin, 'ica_cal_result', f'ica_detection_alarm_{vin}.csv') if not os.path.exists(ica_path): print('No ica detection input!') else: ica_input = ica_produce_alarm(ica_path) soh_path = os.path.join(done_path, vin, 'SOH_cal_result', f'{vin}_sohAno.csv') if not os.path.exists(soh_path): print('No soh detection input!') else: soh_input = soh_produce_alarm(soh_path, vin) alarm_df = pd.concat([isc_input, ica_input, soh_input]) alarm_df.reset_index(drop=True, inplace=True) alarm_df['alarm_cell'] = alarm_df['alarm_cell'].apply(lambda _: str(_)) print(vin) module = AutoAnalysisMain(alarm_df, main_path, data_path, done_path) module.analysis_process() flags = os.O_WRONLY | os.O_CREAT modes = stat.S_IWUSR | stat.S_IRUSR with os.fdopen(os.open(os.path.join(log_path, 'log.txt'), flags, modes), 'w') as txt_file: for k, v in module.output.items(): txt_file.write(k + ':' + str(v)) txt_file.write('\n') for x, y in module.output_sub.items(): txt_file.write(x + ':' + str(y)) txt_file.write('\n\n') fc_result_path = os.path.join(done_path, vin, 'fc_result') if not os.path.exists(fc_result_path): os.makedirs(fc_result_path) pd.DataFrame(module.output).to_csv( os.path.join(fc_result_path, 'main_structure.csv')) df2 = pd.DataFrame() for subs in module.output_sub.keys(): sub_s = pd.Series(module.output_sub[subs]) df2 = df2.append(sub_s, ignore_index=True) df2.to_csv(os.path.join(fc_result_path, 'sub_structure.csv')) end_time = time.time() print("time cost of fault classification:", float(end_time - start_time) * 1000.0, "ms") return
05-28
Here are some suggestions to optimize the code: 1. Use list comprehension to simplify the code: ``` alarm_df = pd.concat([isc_input, ica_input, soh_input]).reset_index(drop=True) alarm_df['alarm_cell'] = alarm_df['alarm_cell'].apply(str) ``` 2. Use context manager to simplify file operation: ``` with open(os.path.join(log_path, 'log.txt'), 'w') as txt_file: for k, v in module.output.items(): txt_file.write(f"{k}:{v}\n") for x, y in module.output_sub.items(): txt_file.write(f"{x}:{y}\n\n") ``` 3. Use `Pathlib` to simplify path operation: ``` fc_result_path = Path(done_path) / vin / 'fc_result' fc_result_path.mkdir(parents=True, exist_ok=True) pd.DataFrame(module.output).to_csv(fc_result_path / 'main_structure.csv') pd.DataFrame(module.output_sub).to_csv(fc_result_path / 'sub_structure.csv') ``` 4. Use f-string to simplify string formatting: ``` print(f"time cost of fault classification: {(end_time - start_time) * 1000.0} ms") ``` Here's the optimized code: ``` def fault_classification_wrapper(vin, main_path, data_path, log_path, done_path): start_time = time.time() isc_path = Path(done_path) / vin / 'isc_cal_result' / f'{vin}_report.xlsx' if not isc_path.exists(): print('No isc detection input!') isc_input = pd.DataFrame() else: isc_input = isc_produce_alarm(isc_path, vin) ica_path = Path(done_path) / vin / 'ica_cal_result' / f'ica_detection_alarm_{vin}.csv' if not ica_path.exists(): print('No ica detection input!') ica_input = pd.DataFrame() else: ica_input = ica_produce_alarm(ica_path) soh_path = Path(done_path) / vin / 'SOH_cal_result' / f'{vin}_sohAno.csv' if not soh_path.exists(): print('No soh detection input!') soh_input = pd.DataFrame() else: soh_input = soh_produce_alarm(soh_path, vin) alarm_df = pd.concat([isc_input, ica_input, soh_input]).reset_index(drop=True) alarm_df['alarm_cell'] = alarm_df['alarm_cell'].apply(str) print(vin) module = AutoAnalysisMain(alarm_df, main_path, data_path, done_path) module.analysis_process() with open(Path(log_path) / 'log.txt', 'w') as txt_file: for k, v in module.output.items(): txt_file.write(f"{k}:{v}\n") for x, y in module.output_sub.items(): txt_file.write(f"{x}:{y}\n\n") fc_result_path = Path(done_path) / vin / 'fc_result' fc_result_path.mkdir(parents=True, exist_ok=True) pd.DataFrame(module.output).to_csv(fc_result_path / 'main_structure.csv') pd.DataFrame(module.output_sub).to_csv(fc_result_path / 'sub_structure.csv') end_time = time.time() print(f"time cost of fault classification: {(end_time - start_time) * 1000.0} ms") return ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值