前言
两个月,C语言快速的入了门,C语言的学习是有趣的,它比java或者python更能看到计算机是怎么实现的,虽然它不是那么的人性化,但这正是机器的特点,C系列语言如果还想好好学习,应该学习计算机组成原理和系统相关知识,希望我能补上吧。
小项目(不简单)
这个小项目主要考察逻辑
//stc.c文件
#include<stdio.h>
#include "stc.h"
#include <stdlib.h>
#include<string.h>
student* students[1000] = { 0 };
int student_count = 0;
void writefile() {
FILE* fw = fopen("C:\\Users\\13726\\Desktop\\cmlearn\\指针\\b.c", "w");
if (fw == NULL) {
return;
}
for (int i = 0; i < student_count; i++) {
fprintf(fw,"%d %s %d\n", students[i]->number, students[i]->name, students[i]->weight);
}
}
void readfile() {
//1.打开文件
FILE* fr = fopen("C:\\Users\\13726\\Desktop\\cmlearn\\指针\\a.c","r");
if (fr == NULL) {
return;
}
//2.读文件
char buffer[128] = { 0 };
while (fgets(buffer, 128, fr) != NULL) {//读一行
//解析字符串(学号 姓名 体重)
paraseString(buffer);
}
//3.写文件
writefile();
//4.释放内存
freestudent();
//5.关闭文件
fclose(fr);
}
void freestudent() {
for (int i = 0; i < student_count; i++) {
free(students[i]);
}
student_count = 0;
}
student* findstudent(int num,int *index) {
for (int i = 0; i < student_count; i++) {
if (students[i]->number == num) {
return students[i];
}
if (students[i]->number > num) {
*index = i;
return NULL;
}
}
*index = student_count;
return NULL;
}
void insertstudent(int index,student* s) {
for (int i = student_count; i > index; i--) {
students[i] = students[i - 1];
}
students[index] = s;
student_count++;
}
void paraseString(char* buffer) {
//1.获得学号
int number = atoi(buffer);
char name[12] = { 0 };
int weight;
//2.过滤数字学号
char* p = buffer;
while (*p != ' ') p++;
//3.过滤空格
while (*p == ' ') {
p++;
}
//4.得到姓名
int i = 0;
while (*p != ' ') {
name[i++] = *p++;
}
//5.得到体重
weight = atoi(p);
//6.去重复,找num相同的
int index = 0;
student* r = findstudent(number,&index);
if (r != NULL) {
//6.1找到了就替换
strcpy(r->name, name);
r->weight = weight;
}
else {
//6.2没找到就重新申请空间,把这个学生放到比num大的学生前面。
student* s = (student*)malloc(sizeof(student));
s->number = number;
strcpy(s->name, name);
s->weight = weight;
insertstudent(index, s);
}
}
//stc.h文件
#pragma once
#ifndef _INC_STC
#define _INC_STC
typedef struct _STUDENT {
int number;
char name[12];
int weight;
}student;
void update();
void paraseString(char* buffer);
void insertstudent(int index, student* s);
student* findstudent(int num, int* index);
void freestudent();
void readfile();
void writefile();
#endif // ! _INC_STC
//主函数
#include<stdio.h>
#include "stc.h"
int main() {
readfile();
return 0;
}