文件操作代码练习

 

main.cpp

// oj_file_operation.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


extern int number_operate(char *inFile, char *outFile);

int main(int argc, char* argv[])
{
 printf("Hello World!\n");

// number_operate("e:\tmp\in_data.txt", "e:\tmp\out_data.txt");
 number_operate("e://tmp/in_data.txt", "e://tmp/out_data.txt");

 return 0;
}

 

 

 

file_read_write.cpp

#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *get_digit_start(char *p_in)
{
 char *p_start = p_in;
 int i = 0;
 //while 循环写法
 //入参检查

 for (i = 0; i < strlen(p_in); i++) //"\n"  
 {
  if (p_in[i] == ' ')
  {
   p_start++;
   continue;
    
  }
  
  if (p_in[i] < '0' || p_in[i] > '9')
  {
   return NULL;
  }

 
  if (p_in[i] >= '0' && p_in[i] <= '9')
  {
   break;
  }
 } 

 return p_start;
}

char *get_digit_end(char *p_in)
{
 char *p_end = p_in;
 int len = 0;
 int i = 0;

 len = strlen(p_in);
 p_end = &p_in[len - 2];  //"\n"

 //相等条件
 while (p_end != p_in)
 {
  if (*p_end < '0' || *p_end > '9')
  {
   return NULL;
  }

  if (*p_end == ' ')
  {
   p_end--;
   continue;
    
  }

  if (*p_end >= '0' && *p_end <= '9')
  {
   break;
  }
 }
  
 return p_end;
}

/*
int is_digit_chars(char *pin)
{
 
}
*/

int number_operate(char *inFile, char *outFile)
{
 FILE *fp = NULL;
 FILE *fp_out = NULL;
 char line_chars[65];
 char out_chars[65];
 char *p_digit_start = NULL;
 char *p_digit_end = NULL;
 char *p_tmp = NULL;
 int i = 0;
 int is_digit_chars = 1;

 if (NULL == (fp = fopen(inFile, "r+")))
 {
  printf(" inFile file opened error");
  perror("perror");
  return -1;
 }

 if (NULL == (fp_out = fopen(outFile, "w+")))
 {
  printf("outFile file opened error");
  perror("perror");
  return -1;
 }

 while (! feof(fp))
 {
  fgets(line_chars, sizeof(line_chars), fp);  //末尾有换行符 \n

  printf("%s\n", line_chars);

  p_digit_start = line_chars;

  if(NULL == ((p_digit_start = get_digit_start(line_chars))))
  {
   continue;
  }

  
  if(NULL == ((p_digit_end = get_digit_end(line_chars))))
  {
   continue;
  }

  p_tmp = p_digit_start;
  while (p_tmp != p_digit_end)
  {
   if (*p_tmp < '0' || *p_tmp > '9')
   {
    is_digit_chars = 0;
    break;
   }

   p_tmp++;
  }

  if (1 != is_digit_chars)
  {
   is_digit_chars = 1;
   continue;
  }

  //should add /n
  strncpy(out_chars, p_digit_start, p_digit_end - p_digit_start + 1);
  out_chars[p_digit_end - p_digit_start + 1] = '\0';
  //out_chars[p_digit_end - p_digit_start + 2] = '\r';
  //out_chars[p_digit_end - p_digit_start + 3] = '\n';
  printf("out file %s \n", out_chars);
  fputs(out_chars, fp_out);
  fputs("\n", fp_out);  //换行
 }

 return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值