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