需要解决的问题:有一个文本,每行由16个 0到f的字符组成(64bit的数字写成十六进制表示),需要统计整个文本中0到f 十六个字符的个数。
matlab做循环运算比较慢,特别在循环次数很多的时候更慢。这时候用C更有优势。按行读取文本,我采用的是fgets()函数。
#include <stdint.h>
#include <stdio.h>
#include <stdint.h>
#include <memory.h>
#include <ctype.h>
int main(){
FILE* fp = fopen("a.txt","r");
if(fp == NULL){
printf("Error: read file failure.\n");
exit(-1);
char txt[1000] = {0}; //存储每行的字符串
uint64_t stat[16] = {0}; //统计
char sample[16] = {'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'};
int i,j;
while(!feof(fp)){
memset(txt, 0, sizeof(txt));
fgets(txt, sizeof(txt-1), fp); //读取一行字符串
if(strlen(txt) != 17) //防止出现异常行
continue;
for(i = 0; i < 16; i++){
for(j = 0; j < 16; j++){
if(txt[i] == sample[j]
stat[j]++;
break;
fclose(fp);
for(i = 0; i < 16; i++){
printf("%u\n", stat[i]);
如果是按2bit统计,那么只需要修改中间部分代码
char sample[4] = {0, 1, 2, 3};
int data, index;
for(i = 0; i < 16; i++){
if(isdigit(txt[i])
data = txt[i] - 48;
else if(isupper(txt[i])
data = txt[i] - 55;
data = txt[i] - 87;
index = data & 0x3;
for(j = 0; j < 4; j++){
if(index == sample[j]){
stat[j]++;
break;
index = (data & 0xc)>>2; //记得右移2位
for(j = 0; j < 4; j++){
if(index == sample[j]){
stat[j]++;
break;
需要解决的问题:有一个文本,每行由16个 0到f的字符组成(64bit的数字写成十六进制表示),需要统计整个文本中0到f 十六个字符的个数。matlab做循环运算比较慢,特别在循环次数很多的时候更慢。这时候用C更有优势。按行读取文本,我采用的是fgets()函数。#include &lt;stdint.h&gt;#include &lt;stdio.h&gt;#include &lt...
在一个问题中遇到了一个小问题,自己试了一下,小结一下
关于
fgets的用法,在man手册中是这样解释的:
char *
fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them
fgets函数用于读取指定文件中的一行,其函数原型为:char * fgets(char * s, int n,FILE *stream);
参数s:将读取的行存入字符型指针s指向的地址
参数n:读取n-1个字符
参数stream:从文件指针stream所指位置的文件缓存区读取
以下做一个示例:
创建一个.csv格式的文档,每一行用“,”隔开
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
在 C 语言中删除
文本文件里的一
行数据, 你需要打开文件并
读取其中的内容, 然后找到要删除的
行, 并将其从文件中删除. 一种方法是将文件的内容
读取到一个
字符串数组中, 在
字符串数组中删除所需的
行, 然后将更新后的
字符串数组写回文件.
下面是一个简单的例子, 它展示了如何使用 C 语言删除
文本文件中的一
行:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_LEN 256
int main(int argc, char *argv[]) {
// 确保文件名和要删除的
行号都已提供
if (argc < 3) {
fprintf(stderr, "Usage: %s filename line_number\n", argv[0]);
return 1;
// 打开文件
FILE *fp = fopen(argv[1], "r");
if (!fp) {
perror("Error opening file");
return 1;
//
读取文件的内容到
字符串数组中
char **lines = NULL;
char line[LINE_LEN];
int line_count = 0;
while (
fgets(line, LINE_LEN, fp)) {
lines = (char **)realloc(lines, sizeof(char *) * (line_count + 1));
lines[line_count] = (char *)malloc(strlen(line) + 1);
strcpy(lines[line_count], line);
line_count++;
// 关闭文件
fclose(fp);
// 将给定
行从
字符串数组中删除
int line_number = atoi(argv[2]);
if (line_number < 1 || line_number > line_count) {
fprintf(stderr, "Error: invalid line number\n");
return 1;
free(lines[line_number - 1]);
for (int i = line_number - 1; i < line_count - 1; i++) {
《Optimized contrast enhancement for real-time image and video dehazing》大气光估计策略
m0_63786384: