1、c的一个例子

(1)文本文件HelloWorld.c

#include <stdio.h>
void main()
{
    printf("Hello World!\n");
}

(2)

不生成HelloWorld.o,直接生成HelloWorld.exe

gcc -o  HelloWorld.exe HelloWorld.c

 

生成HelloWorld.o,再生成HelloWorld.exe

gcc –c HelloWorld.o HelloWorld.c

gcc –o HelloWorld.exe HwlloWorld.c

 

默认生成可执行文件a.out

gcc HelloWorld.c

(3)执行

./HelloWorld.exe

 

 

 

2、C++的一个例子

(1)文本文件helloworld.cpp输入下列内容

#include <iostream>
using namespace std;
int main()
{
    cout<&lt;"Hello World!"&lt;&lt;endl;   
    return 0;
}

(2)g++ –o helloworld.exe helloworld.cpp

(3)./helloworld.exe

注意:

(1)头文件为iostream而不是老版本的iostream.h

(2)指明命名空间,不然会出错。

(3)main 返回 int型,void型会出错。

(4)编译用g++而不是gcc

(5)后缀名为cpp,其它后缀名可能会出错。

 

 

3、C++调用shell

(1)hellosh.cpp文本文件输入以下内容

#include&lt;iostream>  
#include <cstdlib>
using namespace std;
int main()
{   
    for(int i=0;i<2;i++)
    {
        system("ifconfig");   
    }
    return 0;
}

(2)g++ -o hellosh.exe hellosh.cpp

(3)./hellosh.exe

注意:

(1)调用system需包含头文件#include &lt;cstdlib>,不是cstdlib.h

man system可查看需要system包含在哪个头文件里,新版无.h

 

4、linux C++ 打开文件、写入内容

#include<iostream>  
#include<fstream>
#include<iomanip>
using namespace std;

int main()
{   
    ofstream myfile("myinfo.txt");


    if(!myfile) return 0;  //若打开错误则返回

    myfile<&lt;setw(20)&lt;&lt;"name:"&lt;&lt;"ZhangSan"&lt;&lt;endl;
    myfile&lt;&lt;setw(20)&lt;&lt;"address:"&lt;&lt;"china"&lt;&lt;endl;


    myfile.close();


    return 0;
}

 

5、linux c++读取文件内容

#include&lt;iostream>  
#include<cstdlib>
#include<fstream>
#include<iomanip>
using namespace std;

int main()
{   
   

    fstream myfile("myinfo.txt");
    myfile<&lt;1234;
    myfile.close();


    myfile.open("myinfo.txt");


    int myint;
    myfile>&gt;myint;
    cout&lt;&lt;myint&lt;&lt;endl;


    myfile.close();
    return 0;

}

 

注意:非法操作可能会出现乱码,原因可能是文件没有正常打开和关闭。