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;
}