寒假作业2024.2.8

本文介绍了如何编写Makefile以编译C源文件test.c、test1.c和main.c,以及实现字符串计数、单词倒置和文件类型判断的C程序示例。
摘要由CSDN通过智能技术生成

1.现有文件test.c\test1.c\main.c,请编写Makefile

Makefile文件:

CC=gcc
EXE=file
OBJS=$(patsubst %.c,%.o,$(wildcard *.c))
CFLAGS=-c -o
all:$(EXE)

file:test.o test1.o main.o
	@$(CC) $^ -o $@

%.o:%.c
	@$(CC) $(CFLAGS) $@ $^

.PHONY:clean
clean:
	@rm $(OBJS)

 main.c文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
void output(int a,int b);
void fun(int a,int b);
int main(int argc, const char *argv[])
{
	int a=4,b=5;
	output(a,b);
	fun(a,b);
	return 0;
}

test.c文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
void output(int a,int b)
{
	printf("a=%d b=%d\n",a,b);
}

 test1.c文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
void fun(int a,int b)
{
	int sum=a+b;
	printf("sum=%d\n",sum);
}

现象展示:

2.C编程实现: 输入一个字符串,请计算单词的个数
eg: "this is a boy"
输出单词个数:4个

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
	char arr[100];
	printf("please enter arr:");
	gets(arr);
	int num=0;
	for(int i=0;arr[i]!='\0';i++)
	{
		if(arr[i]==' ')
		{
			num++;
		}
	}
	printf("单词的数量为%d\n",num+1);
	return 0;
}

现象展示:

 3.在终端输入一个文件名,判断文件的类型

#!/bin/bash

read -p "please enter filename:" file

if [ -b $file ]
then 
	echo "块设备文件"
elif [ -c $file ]
then
	echo "字符设备文件"
elif [ -d $file ]
then
	echo "目录"
elif [ -L $file ]
then
	echo "软连接文件"
elif [ -p $file ]
then
	echo "管道文件"
elif [ -s $file ]
then
	echo "套接文件"
elif [ -f $file ]
then
	echo "普通文件"
else
	echo "文件不存在"
fi

现象展示:

4.C编程实现
字符串倒置:(注意:是倒置,而不是直接倒置输出)
原字符串为:char *str =“I am Chinese
倒置后为:“Chinese am I”
附加要求:删除原本字符串中多余的空格 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
	char str[100];
	printf("please enter str:");
	gets(str);
	int len=strlen(str);
	int i,j;
	for (i=0,j=0;i<len;i++) //删除原本字符串中多余空格
	{
        if (str[i]!=' ' || (i>0 && str[i-1]!=' ')) 
		{
            str[j]=str[i];
			j++;
        }
    }
    str[j]='\0';
	puts(str);

	i=0,j=strlen(str)-1;//整体逆置
	while(i<j)
	{
		char t=str[i];
		str[i]=str[j];
		str[j]=t;
		i++;
		j--;
	}
	i=j=0;
	while(str[i]!='\0')//单词逆置
	{
		while(str[j]!=' ' && str[j]!='\0')
		{
			j++;
		}
		int k=j-1;
		while(i<k)
		{
			char t=str[i];
			str[i]=str[k];
			str[k]=t;
			i++;
			k--;
		}
		while(str[j]==' ')
		{
			j++;
		}
		i=j;
	}
	puts(str);
	return 0;
}

现象展示:

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值