linuxc编程实例
《Linux C编程》是2005-12-30出版的一本图书,本书系统地介绍了在Linux平台下用c语言进行程序开发的过程,通过列举大量的程序实例,使读者很快掌握在Linux平台下进行C程序开发的方法和技巧,并具备开发大型应用程序的能力。本书系统地介绍了在Linux平台下用C语言进行程序开发的过程,通过列举大量的程序实例,使读者很快掌握在Linux平台下进行C程序开发的方法和技巧,并具备开发大型应用程序的能力。本书内容翔实,主要包括:Linux平台下C语言及其编程环境的介绍,C语言编译器、调试工具和自动维护工具的使用方法,Linux系统提供的特有函数调用,在C程序中访问文件的方法言网络编程方法以及curses编程等。《linux c从入门到精通编程》从初学者的角度出发,通过通俗易懂的语言,丰富多彩的实例,详细介绍丁在linux系统下使用c语言进行应用程序开发应该掌握的各方面技术。全书共分20章,包括linux系统概述、c语言基础、内存管理、基本编辑器vim和emacs、gcc编译器、gdb调试工具、进程控制、进程间通信、文件操作、文件的输入/输出操作、信号及信号处理、网络编程、make编译基础、linux系统下的c语言与数据库、集成开发环境、界面开发基础、界面布局、界面构件开发、glade设计程序界面、mp3音乐播放器。所有知识都结合具体实例进行介绍,涉及的程序代码给出了详细的注释,可以使读者轻松领会linux系统下的c语言应用程序开发的精髓,快速提高开发技能。
2. linux c编程
/*
Name: list.c
Author: guozan _SCS_BUPT
Mail: [email protected]
Date: 2010/4/6
实验目的:练习vi,使用UNIX的系统调用和库函数,体会UNIX文件通配符的处理方式以及命令对选项的处理方式。
编程实现程序list.c,列表普通磁盘文件(不考虑目录和设备文件等),列出文件名和文件大小。
与ls命令类似,命令行参数可以有0到多个
0个参数:列出当前目录下所有文件
参数为普通文件:列出文件
参数为目录:列出目录下所有文件
实现自定义选项r,a,l,h,m以及--
r 递归方式列出子目录
a 列出文件名第一个字符为圆点的普通文件(默认情况下不列出文件名首字符为圆点的文件)
l 后跟一整数,限定文件大小的最小值(字节)
h 后跟一整数,限定文件大小的最大值(字节)
m 后跟一整数n,限定文件的最近修改时间必须在n天内
-- 显式地终止命令选项分析
*/
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
/*
slective options about ls
rflag is about recursive
aflag is about ones with . infront
lflag is about the minimum size
hflag is about the maximum size
mflag is about the modified time
*/
int rflag, aflag, lflag, hflag, mflag;
long modified_time; //the last time file be modified, days ago
off_t lower_size; //file's minimum size
off_t upper_size; //file's maximum size
/*
set the flags, thus the ls option
*/
void getoptions(int argc, char *argv[])
{
char ch;
//clear, all unseted
rflag = 0; aflag = 0; lflag = 0; hflag = 0; mflag = 0;
//use getopt to get the options, want to know more, call man
//the last one or after -- was set in argv[optind]
while ((ch = getopt(argc, argv, "ral:h:m:")) != -1) {
switch (ch) {
case 'r': rflag = 1; break;
case 'a': aflag = 1; break;
case 'l': lflag = 1; lower_size = atol(optarg); break;
case 'h': hflag = 1; upper_size = atol(optarg); break;
case 'm': mflag = 1; modified_time = atol(optarg); break; //get days
case '?': printf("Unknown option: %c\n", (char)optopt); break;
default : printf("Step into default\n"); break;
}
}
}
/*
the function to list things in path
*/
int ls(char *path)
{
struct stat st; //for check this is a directory or file
char temp[100]; //if path is null, it is used to get current directory
// get the path
if (path == NULL || path[0] == '-') {
path = temp;
getcwd(path, 100);
}
/* open the inode of file */
if (lstat(path, &st)) {
fprintf(stderr, "Error: %s not exist.\n", path);
return (-1);
}
/* judge whether the file is a file or a directory */
if (S_ISDIR(st.st_mode)) {
ls_dir(path);
}
else if (S_ISREG(st.st_mode)) {
print(path);
}
else {
printf("Not ordinary file, wouldn't be listed.\n");
}
return 0;
}
/*
list dirs, may recursively or not, depending on rflag
one thing is sure that it will list directories and files first,
then consider the things in the directories
*/
int ls_dir(char *path)
{
DIR *dp = NULL;
struct dirent *dirp = NULL;
if (path[0] != '.' || (path[0] == '.' && aflag == 1)) {
printf("\n%s:\n****************************************\n", path);
/* open the directory */
if ((dp = opendir(path)) == NULL) {
fprintf(stderr, "Error: can't open directory %s!\n", path);
return (-1);
}
chdir(path);
/* list all the things in directory */
while ((dirp = readdir(dp)) != NULL) {
print(dirp->d_name);
}
/* recursively ls dirs, after ls things together,
it's time to list things in children directory */
if (rflag == 1) {
rewinddir(dp); //reset dp
while ((dirp = readdir(dp)) != NULL) {
if (strcmp(dirp->d_name, ".") == 0
|| strcmp(dirp->d_name, "..") == 0) { //no current and parent directory
continue;
}
ls_dir_r(dirp->d_name); //only list directories, judged inside the function
}
}
/* close the directory */
if (closedir(dp)) {
fprintf(stderr, "Error: can't close the directory %s!\n", path);
return -1;
}
chdir("..");
}
return 0;
}
/*
list directories recursively,
only directories, nomatter what path you put in
*/
int ls_dir_r(char *path)
{
struct stat st;
/* open the inode of file */
if (lstat(path, &st)) {
fprintf(stderr, "Error: %s not exist.\n", path);
return (-1);
}
/* only ls directories */
if (S_ISDIR(st.st_mode)) {
ls_dir(path);
}
}
/*
print the filetype/size/name on the screen
*/
int print(char *path)
{
struct stat st;
time_t tp;
char *filename = NULL;
//get current time
time(&tp);
if (lstat(path, &st)) {
fprintf(stderr, "Error: %s can't be opened.\n", path);
return (-1);
}
/* get file name */
if ((filename = strrchr(path, '/')) != NULL) {
filename++;
}
else {
filename = path;
}
/* judge whether to list the file */
if ((S_ISDIR(st.st_mode)|| S_ISREG(st.st_mode)) //only directories and normal files
&& (lflag == 0 || (lflag == 1 && (st.st_size >= lower_size))) //the min size
&& (hflag == 0 || (hflag == 1 && (st.st_size <= upper_size))) //the max size
&& (mflag == 0 || (mflag == 1 && ((tp - st.st_mtime) <= modified_time * 24 * 60 * 60))) //modified time
&& (aflag == 1 || (aflag == 0 && filename[0] != '.')) //file with a '.' infront
) {
printf("%s\t%10ld\t%s\n", (S_ISDIR(st.st_mode) ? "DIR": "FILE"), st.st_size, filename);
}
return 0;
}
/*
The main function
*/
int main(int argc, char *argv[])
{
getoptions(argc, argv);
ls(argv[optind]);
return 0;
}
3. linux下的C编程
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char *memory, *b;
void ShareMemory( char func, char *data )
{
switch( func )
{
case 'c':
memory = ( char * )malloc( sizeof( char ) * 64 );
break;
case 'r':
printf( "%s", memory );
break;
case 'w':
strcpy( memory, data );
break;
case 'd':
free( memory );
break;
default:
printf("wrong input!");
}
}
void main(int argc,char **argv)
{
ShareMemory( *argv[1], argv[2] );
ShareMemory( *argv[3], argv[4] );
ShareMemory( *argv[5], argv[6] );
}
提供个思路,这个程序只能在一次运行中解决问题,比如程序名是oo输入oo c a w hello r a就可以输出hello,至于怎么使用上次运行建立的内存我也不知道。
4. 在Linux系统中,如何运行一个C语言程序
1、打开kali linux的终端。创建一个文件并命名为test.c。在终端输入:touch test.c。
5. 怎样学习在linux操作系统下用C语言编程
Linux下C语言编程基础知识:
1.源程序的编译
在Linux下面,如果要编译一个C语言源程序,我们要使用GNU的gcc编译器. 下面我们以一个实例来说明如何使用gcc编译器.
假设我们有下面一个非常简单的源程序(hello.c):
int main(int argc,char **argv)
{
printf("Hello Linuxn");
}
要编译这个程序,我们只要在命令行下执行:
gcc -o hello hello.c
gcc 编译器就会为我们生成一个hello的可执行文件.执行./hello就可以看到程序的输出结果了.命令行中 gcc表示我们是用gcc来编译我们的源程序,-o 选项表示我们要求编译器给我们输出的可执行文件名为hello 而hello.c是我们的源程序文件.
gcc编译器有许多选项,一般来说我们只要知道其中的几个就够了. -o选项我们已经知道了,表示我们要求输出的可执行文件名. -c选项表示我们只要求编译器输出目标代码,而不必要输出可执行文件. -g选项表示我们要求编译器在编译的时候提供我们以后对程序进行调试的信息.
知道了这三个选项,我们就可以编译我们自己所写的简单的源程序了,如果你想要知道更多的选项,可以查看gcc的帮助文档,那里有着许多对其它选项的详细说明.
2.Makefile的编写
假设我们有下面这样的一个程序,源代码如下:
/* main.c */
#include "mytool1.h"
#include "mytool2.h"
int main(int argc,char **argv)
{
mytool1_print("hello");
mytool2_print("hello");
}
/* mytool1.h */
#ifndef _MYTOOL_1_H
#define _MYTOOL_1_H
void mytool1_print(char *print_str);
#endif
/* mytool1.c */
#include "mytool1.h"
void mytool1_print(char *print_str)
{
printf("This is mytool1 print %sn",print_str);
}
/* mytool2.h */
#ifndef _MYTOOL_2_H
#define _MYTOOL_2_H
void mytool2_print(char *print_str);
#endif
/* mytool2.c */
#include "mytool2.h"
void mytool2_print(char *print_str)
{
printf("This is mytool2 print %sn",print_str);
}
当然由于这个程序是很短的我们可以这样来编译
gcc -c main.c
gcc -c mytool1.c
gcc -c mytool2.c
gcc -o main main.o mytool1.o mytool2.o
这样的话我们也可以产生main程序,而且也不时很麻烦.但是如果我们考虑一下如果有一天我们修改了其中的一个文件(比如说mytool1.c)那么我们难道还要重新输入上面的命令?也许你会说,这个很容易解决啊,我写一个SHELL脚本,让她帮我去完成不就可以了.是的对于这个程序来说,是可以起到作用的.但是当我们把事情想的更复杂一点,如果我们的程序有几百个源程序的时候,难道也要编译器重新一个一个的去编译?
为此,聪明的程序员们想出了一个很好的工具来做这件事情,这就是make.我们只要执行以下make,就可以把上面的问题解决掉.在我们执行make 之前,我们要先编写一个非常重要的文件.--Makefile.对于上面的那个程序来说,可能的一个Makefile的文件是:
# 这是上面那个程序的Makefile文件
main:main.o mytool1.o mytool2.o
gcc -o main main.o mytool1.o mytool2.o
main.o:main.c mytool1.h mytool2.h
gcc -c main.c
mytool1.o:mytool1.c mytool1.h
gcc -c mytool1.c
mytool2.o:mytool2.c mytool2.h
gcc -c mytool2.c
有了这个Makefile文件,不过我们什么时候修改了源程序当中的什么文件,我们只要执行make命令,我们的编译器都只会去编译和我们修改的文件有关的文件,其它的文件她连理都不想去理的.
下面我们学习Makefile是如何编写的.
在Makefile中也#开始的行都是注释行.Makefile中最重要的是描述文件的依赖关系的说明.一般的格式是:
target: components
TAB rule
第一行表示的是依赖关系.第二行是规则.
比如说我们上面的那个Makefile文件的第二行
main:main.o mytool1.o mytool2.o
表示我们的目标(target)main的依赖对象(components)是main.o mytool1.o mytool2.o 当倚赖的对象在目标修改后修改的话,就要去执行规则一行所指定的命令.就象我们的上面那个Makefile第三行所说的一样要执行 gcc -o main main.o mytool1.o mytool2.o 注意规则一行中的TAB表示那里是一个TAB键
Makefile有三个非常有用的变量.分别是$@,$^,$<代表的意义分别是:
$@--目标文件,$^--所有的依赖文件,$<--第一个依赖文件.
如果我们使用上面三个变量,那么我们可以简化我们的Makefile文件为:
# 这是简化后的Makefile
main:main.o mytool1.o mytool2.o
gcc -o $@ $^
main.o:main.c mytool1.h mytool2.h
gcc -c $<
mytool1.o:mytool1.c mytool1.h
gcc -c $<
mytool2.o:mytool2.c mytool2.h
gcc -c $<
经过简化后我们的Makefile是简单了一点,不过人们有时候还想简单一点.这里我们学习一个Makefile的缺省规则
.c.o:
gcc -c $<
这个规则表示所有的 .o文件都是依赖与相应的.c文件的.例如mytool.o依赖于mytool.c这样Makefile还可以变为:
# 这是再一次简化后的Makefile
main:main.o mytool1.o mytool2.o
gcc -o $@ $^
.c.o:
gcc -c $<
好了,我们的Makefile 也差不多了,如果想知道更多的关于Makefile规则可以查看相应的文档.
3.程序库的链接
试着编译下面这个程序
/* temp.c */
#include <math.h>
int main(int argc,char **argv)
{
double value;
printf("Valuefn",value);
}
这个程序相当简单,但是当我们用 gcc -o temp temp.c 编译时会出现下面所示的错误.
/tmp/cc33Ky.o: In function `main':
/tmp/cc33Ky.o(.text+0xe): undefined reference to `log'
collect2: ld returned 1 exit status
出现这个错误是因为编译器找不到log的具体实现.虽然我们包括了正确的头文件,但是我们在编译的时候还是要连接确定的库.在Linux下,为了使用数学函数,我们必须和数学库连接,为此我们要加入 -lm 选项. gcc -o temp temp.c -lm这样才能够正确的编译.也许有人要问,前面我们用printf函数的时候怎么没有连接库呢?是这样的,对于一些常用的函数的实现,gcc编译器会自动去连接一些常用库,这样我们就没有必要自己去指定了. 有时候我们在编译程序的时候还要指定库的路径,这个时候我们要用到编译器的 -L选项指定路径.比如说我们有一个库在 /home/hoyt/mylib下,这样我们编译的时候还要加上 -L/home/hoyt/mylib.对于一些标准库来说,我们没有必要指出路径.只要它们在起缺省库的路径下就可以了.系统的缺省库的路径/lib /usr/lib /usr/local/lib 在这三个路径下面的库,我们可以不指定路径.
还有一个问题,有时候我们使用了某个函数,但是我们不知道库的名字,这个时候怎么办呢?很抱歉,对于这个问题我也不知道答案,我只有一个傻办法.首先,我到标准库路径下面去找看看有没有和我用的函数相关的库,我就这样找到了线程(thread)函数的库文件(libpthread.a). 当然,如果找不到,只有一个笨方法.比如我要找sin这个函数所在的库. 就只好用 nm -o /lib/*.so|grep sin>~/sin 命令,然后看~/sin文件,到那里面去找了. 在sin文件当中,我会找到这样的一行libm-2.1.2.so:00009fa0 W sin 这样我就知道了sin在 libm-2.1.2.so库里面,我用 -lm选项就可以了(去掉前面的lib和后面的版本标志,就剩下m了所以是 -lm). 如果你知道怎么找,请赶快告诉我,我回非常感激的.谢谢!
4.程序的调试
我们编写的程序不太可能一次性就会成功的,在我们的程序当中,会出现许许多多我们想不到的错误,这个时候我们就要对我们的程序进行调试了.
最常用的调试软件是gdb.如果你想在图形界面下调试程序,那么你现在可以选择xxgdb.记得要在编译的时候加入 -g选项.关于gdb的使用可以看gdb的帮助文件.由于我没有用过这个软件,所以我也不能够说出如何使用. 不过我不喜欢用gdb.跟踪一个程序是很烦的事情,我一般用在程序当中输出中间变量的值来调试程序的.当然你可以选择自己的办法,没有必要去学别人的.现在有了许多IDE环境,里面已经自己带了调试器了.你可以选择几个试一试找出自己喜欢的一个用.
5.头文件和系统求助
有时候我们只知道一个函数的大概形式,不记得确切的表达式,或者是不记得着函数在那个头文件进行了说明.这个时候我们可以求助系统.
比如说我们想知道fread这个函数的确切形式,我们只要执行 man fread 系统就会输出着函数的详细解释的.和这个函数所在的头文件<stdio.h>说明了. 如果我们要write这个函数的说明,当我们执行man write时,输出的结果却不是我们所需要的. 因为我们要的是write这个函数的说明,可是出来的却是write这个命令的说明.为了得到write的函数说明我们要用 man 2 write. 2表示我们用的write这个函数是系统调用函数,还有一个我们常用的是3表示函数是C的库函数.
记住不管什么时候,man都是我们的最好助手.
6. 在Linux下如何开发C程序
在Linux开发环境下,GCC是进行C程序开发不可缺少的编译工具。GCC是GNU C Compile的缩写,是GNU/Linux系统下的标准C编译器。虽然GCC没有集成的开发环境,但堪称是目前效率很高的C/C++编译器。《linux就该这么学》非常值得您一看。Linux平台下C程序开发步骤如下:
1.利用编辑器把程序的源代码编写到一个文本文件中。
比如编辑test.c程序内容如下:
/*这是一个测试程序*/
#include<stdio.h>
int main(void)
{
printf("Hello Linux!");
}
2.用C编译器GCC编译连接,生成可执行文件。
$gcc test.c
编译完成后,GCC会创建一个名为a.out的文件。如果想要指定输出文件,可以使用选项-o,命令如下所示:
$gcc-o test1 test.c
这时可执行文件名就变为test1,而不是a.out。
3.用C调试器调试程序。
4.运行该可执行文件。 在此例中运行的文件是:
$./a.out 或者 test1
结果将得出:
Hello Linux!
除了编译器外,Linux还提供了调试工具GDB和程序自动维护工具Make等支持C语言编程的辅助工具。如果想要了解GCC的所有使用说明,使用以下命令:
$man gcc
7. Linux下C语言编程用的readdir()实例
第一:linux下不成认无返回值的main方法
第二:你这个若成功,也只能够读取/etc/rc.d目录下的内容
#include<sys/types.h>
#include <stdio.h>
#include<dirent.h>
#include<unistd.h>
int main(int argc,char **argv)
{
DIR * dir;
struct dirent * ptr;
int i;
if(argc==1)
dir=opendir("./");
else
dir=opendir(argv[1]);
while((ptr=readdir(dir))!=NULL)
{
printf("d_name: %s\n",ptr->d_name);//需要更详细的信息你可以修改该句
}
closedir(dir);
return 0;
}
8. 到底怎么在Linux里编写c程序啊
在linux下通常使用gedit或vim直接编写.c程序,然后通过gcc指令编译。以Ubuntu系统为例,详细过程如下:
1、进入桌面Temp文件夹
9. 基于Linux下的C语言编程
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int
main()
{
intfd;
char*p="hello";
charbuf[256]={0};
if(-1!=(fd=open("./new.txt",O_RDWR)))
{
if(-1!=write(fd,p,strlen(p)))
{
printf("WRITEOK ");
}
else
printf("WRITEFAILED ");
close(fd);
}
if(-1!=(fd=open("./new.txt",O_RDONLY)))
{
if(-1!=read(fd,buf,256))
printf("READ:%s ",buf);
close(fd);
}
return0;
}