美文网首页
C语言编程基本原理和实践

C语言编程基本原理和实践

作者: liamu | 来源:发表于2018-05-20 22:27 被阅读5次

Makefile的编写

  • Makefile文件内容如下
# this is make file 注释
hello.out:max.o min.o hello.c
        gcc max.o min.o hello.c
max.o:max.c
        gcc -c max.c
min.o:min.c
        gcc -c min.c
  • 当前文件夹文件情况
amu@amu:~/workplace/les1$ ls
hello.c  Makefile  max.c  max.h  min.c  min.h

命令参数的获取

  • 源代码如下
#include <stdio.h>

int main(int argv,char* argc[])
{
    printf("hello word %d\n",argv);
    int i;
    for(i=0;i< argv;i++){
        printf("argc[%d] is %s \n",i,argc[i]);
    }
    return 0;
}
  • 运行结果
amu@amu:~/workplace/les2$ ./main3 test test1 test3
hello word 4
argc[0] is ./main3 
argc[1] is test 
argc[2] is test1 
argc[3] is test3 

标准的输入输出流和错误流

  • 源代码
#include <stdio.h>

int main()
{
    fprintf(stdout,"please enter value a : \n");
    // 相当于printf(),stdout指代终端输出,如果这里有打印机,可以指定打印机输出,如果给的是文件句柄则可以输出到文件

    int a;
    // scanf("%d",&a);
    fscanf(stdin,"%d",&a);

    if(a<0){
        fprintf(stderr,"the value must > 0\n");//错误流的输出指定
        return 1;
    }
    return 0;
}
  • 运行结果
amu@amu:~/workplace/les3$ ./test 
please enter value a : 
45
amu@amu:~/workplace/les3$ ./test 
please enter value a : 
-2
the value must > 0

标准的输入输出流和错误流重定向

  • 源代码
#include <stdio.h>

int main()
{
    int i,j;
    printf("please i:\n");
    scanf("%d",&i);
    printf("please j:\n");
    scanf("%d",&j);
    printf("sum = i + j = %d\n",i+j);
}
  • input.txt文件内容
4
7
  • 运行结果
amu@amu:~/workplace/les4$ ./a.out < input.txt 
please i:
please j:
sum = i + j = 11

使用C做个小程序

  • vim flag.c
#include <stdio.h>

int main()
{
    int flag = 1;
    int i;
    int count = 0;
    int s = 0;
    while(flag){
        scanf("%d",&i);
        if(0==i) break;
        count++;
        s+=i;
    }
    printf("%d,%d \n",s,count);
    return 0;
}
  • vim main.c
#include <stdio.h>

int main()
{
    int s,n;
    scanf("%d,%d",&s,&n);
    float v = s/n;
    printf("%f\n",v);
    return 0;
}
  • 运行结果
amu@amu:~/workplace/les5$ ./flag | ./main
900
800
700
0
800.000000

相关文章

网友评论

      本文标题:C语言编程基本原理和实践

      本文链接:https://www.haomeiwen.com/subject/olxxjftx.html