c上傳文件代碼
❶ c語言文件傳輸
伺服器端(發送文件):首先打開文件【fopen】,用rb方式打開,既可以發送文本文件,也可以發送二進制文件,在無錯時初始化套接字socket,即初始化socket庫【WSAStartup】,分配socket【socket】,填充伺服器的地址,即填充sockaddr_in結構,然後進行綁定【bind】,設置套接字為監聽套接字【listen】,接收連接【accept】,至此伺服器阻塞,等待客戶端的連接。
客戶端(接收文件):首先打開文件【fopen】,用wb方式打開,在無錯時初始化套接字socket,即初始化socket庫【WSAStartup】,分配socket【socket】,填充客戶端的地址,即填充sockaddr_in結構,然後進行綁定【bind】,再填充伺服器的地址結構,然後調用【connect】進行連接,當連接成功後,第一階段的工作便結束了。
第二階段,發送文件。
伺服器端:使用循環while,結束條件是(!feof(fp)),fp是文件指針,feof檢測當前的文件讀取指針是否到達文件尾部,若到達了就返回真,否則返回假。然後在循環內部依次調用【fread】、【send】進行發送。這里有一個問題需要注意,調用fread的時候有兩個參數是要每次讀多少位元組和讀多少次,將第一個設置為1,將第二個設置為緩沖區的大小,用一個變數記錄實際讀到多少位元組,即【fread】的返回值,然後將其傳遞給【send】,就可以實現發送文件了,在發送完成後斷開連接【closesocket】,關閉文件【fclose】。
客戶端:使用while死循環,調用【recv】接收文件,【fwrite】寫入文件,這里也有個和上面類似的問題,就是要將recv的返回值傳遞給fwrite的第三個參數,即受到了多少位元組,就向文件中寫多少位元組。當recv返回值為0時(連接斷開時)退出循環,【closesocket】關閉套接字,調用【fclose】關閉文件。
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
structPCB{
charNAME[10];/*進程名*/
intROUND;/*進程輪轉時間片*/
intREACHTIME;/*進程到達時間*/
intCPUTIME;/*進程佔用CPU時間*/
intCOUNT;/*計數器*/
intNEEDTIME;/*進程完成還要的CPU時間*/
charSTATE;/*進程的狀態*/
structPCB*NEXT;/*鏈指針*/
};
structLINK{/*PCB的鏈結構*/
structPCB*RUN;/*當前運行進程指針*/
structPCB*READY;/*就緒隊列頭指針*/
structPCB*TAIL;/*就緒隊列尾指針*/
structPCB*FINISH;/*完成隊列頭指針*/
};
voidINIT(LINK*);/*對PCB的鏈結構初始化*/
voidINSERT(LINK*);/*將執行了一個單位時間片數且還未完成的進程的PCB插到就緒隊列的隊尾*/
voidFIRSTIN(LINK*);/*將就緒隊列中的第一個進程投入運行*/
voidPRINT(LINK*);/*列印每執行一個時間片後的所有進程的狀態*/
voidPR(PCB*);/*列印一個進程的狀態*/
intCREATE(LINK*,int);/*創建新的進程*/
voidROUNDSCH(LINK*);/*按時間片輪轉法調度進程*/
voidmain(){
LINKpcbs;
inti;
INIT(&pcbs);
i=0;
printf("創建5個進程 ");
while(i<5){
if(CREATE(&pcbs,i+1)==1){
printf("進程已創建 ");
i++;
}
else
printf("進程創建失敗 ");
}
FIRSTIN(&pcbs);
ROUNDSCH(&pcbs);
}
voidROUNDSCH(LINK*p){
PCB*pcb;
while(p->RUN!=NULL){
pcb=(PCB*)malloc(sizeof(PCB));
strcpy(pcb->NAME,p->RUN->NAME);
pcb->ROUND=p->RUN->ROUND;
pcb->REACHTIME=p->RUN->REACHTIME;
pcb->CPUTIME=p->RUN->CPUTIME;
pcb->COUNT=p->RUN->COUNT;
pcb->NEEDTIME=p->RUN->NEEDTIME;
pcb->STATE=p->RUN->STATE;
pcb->NEXT=p->RUN->NEXT;
pcb->CPUTIME++;
pcb->NEEDTIME--;
pcb->COUNT++;
if(pcb->NEEDTIME==0){
pcb->NEXT=p->FINISH->NEXT;
p->FINISH->NEXT=pcb;
pcb->STATE='F';
p->RUN=NULL;
if(p->READY!=p->TAIL)
FIRSTIN(p);
}
else{
p->RUN=pcb;
if(pcb->COUNT==pcb->ROUND){
pcb->COUNT=0;
if(p->READY!=p->TAIL){
pcb->STATE='W';
INSERT(p);
FIRSTIN(p);
}
}
}
PRINT(p);
}
}
voidINIT(LINK*p){
p->RUN=NULL;
p->TAIL=p->READY=(PCB*)malloc(sizeof(PCB));
p->READY->NEXT=NULL;
p->FINISH=(PCB*)malloc(sizeof(PCB));
p->FINISH->NEXT=NULL;
}
intCREATE(LINK*p,intn){
PCB*pcb,*q;
pcb=(PCB*)malloc(sizeof(PCB));
flushall();
printf("請輸入第%d個進程的名稱: ",n);
gets(pcb->NAME);
printf("請輸入第%d個進程的輪轉時間片數: ",n);
scanf("%d",&(pcb->ROUND));
printf("請輸入第%d個進程的到達時間: ",n);
scanf("%d",&(pcb->REACHTIME));
pcb->CPUTIME=0;
pcb->COUNT=0;
printf("請輸入第%d個進程需運行的時間片數: ",n);
scanf("%d",&(pcb->NEEDTIME));
pcb->STATE='W';
pcb->NEXT=NULL;
if(strcmp(pcb->NAME,"")==0||pcb->ROUND<=0||pcb->NEEDTIME<=0)/*輸入錯誤*/
return0;
q=p->READY;
while(q->NEXT!=NULL&&q->NEXT->REACHTIME<=pcb->REACHTIME)
q=q->NEXT;
pcb->NEXT=q->NEXT;
q->NEXT=pcb;
if(pcb->NEXT==NULL)
p->TAIL=pcb;
return1;
}
voidFIRSTIN(LINK*p){
PCB*q;
q=p->READY->NEXT;
p->READY->NEXT=q->NEXT;
q->NEXT=NULL;
if(p->READY->NEXT==NULL)
p->TAIL=p->READY;
q->STATE='R';
p->RUN=q;
}
voidINSERT(LINK*p){
PCB*pcb;
pcb=(PCB*)malloc(sizeof(PCB));
strcpy(pcb->NAME,p->RUN->NAME);
pcb->ROUND=p->RUN->ROUND;
pcb->REACHTIME=p->RUN->REACHTIME;
pcb->CPUTIME=p->RUN->CPUTIME;
pcb->COUNT=p->RUN->COUNT;
pcb->NEEDTIME=p->RUN->NEEDTIME;
pcb->STATE=p->RUN->STATE;
pcb->NEXT=p->RUN->NEXT;
p->TAIL->NEXT=pcb;
p->TAIL=pcb;
p->RUN=NULL;
pcb->STATE='W';
}
voidPRINT(LINK*p){
PCB*pcb;
printf("執行一個時間片後的所有進程的狀態: ");
if(p->RUN!=NULL)
PR(p->RUN);
if(p->READY!=p->TAIL){
pcb=p->READY->NEXT;
while(pcb!=NULL){
PR(pcb);
pcb=pcb->NEXT;
}
}
pcb=p->FINISH->NEXT;
while(pcb!=NULL){
PR(pcb);
pcb=pcb->NEXT;
}
}
voidPR(PCB*p){
printf("進程名:%s ",p->NAME);
printf("進程輪轉時間片:%d ",p->ROUND);
printf("進程到達時間:%d ",p->REACHTIME);
printf("進程佔用CPU時間:%d ",p->CPUTIME);
printf("計數器:%d ",p->COUNT);
printf("進程完成還要的CPU時間:%d ",p->NEEDTIME);
printf("進程的狀態:%c ",p->STATE);
}
❸ C#使用HTML文件中的file文件上傳,用C#代碼接收上傳文件
<formid="form1"method="post"enctype="multipart/form-data"action="test.aspx">
<inputid="File1"type="file"name="File1"/>
<inputid="Submit1"type="submit"value="submit"/>
</form>
c# 代碼 test.aspx.cs後台代碼如下:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclasstest:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(Request.Files.Count>0)
{
HttpPostedFilef=Request.Files[0];
f.SaveAs(Server.MapPath("test.dat"));
}
}
}
❹ c#如何實現將文件上傳到伺服器求詳細代碼謝了
//文件寫入流
private void ReadFile()
{
Byte[] MesageFile;
string path =@"c:\123.XML";
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
int size = Convert.ToInt32(stream.Length);
MesageFile = new Byte[size];
stream.Read(MesageFile, 0, size);
stream.Close()
string fileName =path.Substring(path.LastIndexOf("\\") + 1, path.Length path.LastIndexOf("\\") - 1);
WriteFile(MesageFile, fileName);
}
//寫入文件
private void WriteFile(Byte[] fileByte,string fileName)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\UpLoad\\" + DateTime.Now.ToString("yyyy-MM-dd")+"\\";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string savepath = path + fileName;
FileStream fos = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fos.Write(MesageFile, 0, MesageFile.Length);
fos.Close();
}
上傳的文件格式不限。
❺ c# ftp方式上傳文件到指定伺服器 代碼求詳細點 先手啦!
//這是個一個C#上傳文件的例子,你參考參考
usingSystem.Net;
usingSystem.IO;
privateFtpStatusCodeUploadFun(stringfileName,stringuploadUrl)
{
StreamrequestStream=null;
FileStreamfileStream=null;
FtpWebResponseuploadResponse=null;
try
{
FtpWebRequestuploadRequest=
(FtpWebRequest)WebRequest.Create(uploadUrl);
uploadRequest.Method=WebRequestMethods.Ftp.UploadFile;
uploadRequest.Proxy=null;宴余
NetworkCredentialnc=newNetworkCredential();
nc.UserName="aa";
nc.Password="aa123";
uploadRequest.Credentials=nc;//修改getCredential();錯誤2
requestStream=uploadRequest.GetRequestStream();
fileStream=File.Open(fileName,FileMode.Open);
byte[]buffer=newbyte[1024];
intbytesRead;
while滾祥扒(true)
{
bytesRead=fileStream.Read(buffer,0,buffer.Length);
if(bytesRead==0)
break;
requestStream.Write(buffer,0,bytesRead);
}
requestStream.Close();
uploadResponse=(FtpWebResponse)uploadRequest.GetResponse();
returnuploadResponse.StatusCode;
}
catch(UriFormatExceptionex)
{
}
catch(IOExceptionex)
{
}
catch(WebExceptionex)
{
}
finally
{
if(uploadResponse!=null)
uploadResponse.Close();
if(fileStream!=null)
fileStream.Close();
if(requestStream!=null)
requestStream.Close();
}
returnFtpStatusCode.Undefined;
}
//這么調用:
FtpStatusCodestatus=大昌UploadFun(@"d:11.txt","ftp://域名/目錄/保存文件名");
❻ 如何把c的文件打包上傳到pypi,讓用戶通過pip安裝的時候編譯c的代碼
使用distutils.core中的Extension函數即可。具體方法為,在setup.py中,添加如下代碼:
my_c_exten = Extension('期望編寬槐陪譯後的庫名', sources=['c庫文件的相對路徑'])
setup(
...
ext_moles=[my_c_exten],
)
這樣,在打包時,指定的c庫文明顫件也會被上傳慎蠢上去,在用戶執行install時,就會在安裝目錄中(例如是lib/python2.7/site-packages/)中生成把這個c文件進行編譯。這樣就可以python代碼中調用該庫了。
❼ 如何用c語言實現上傳文件
FTP 是File Transfer Protocol(文件傳輸協議)的英文簡稱,而中文簡稱為「文傳協議」。
1.C語言可以使用CStdioFile函數打開本地文件。使用類CInternetSession 創建並初始化一個Internet打開FTP伺服器文件。
CStdioFile繼承自CFile,一個CStdioFile 對象代表一個用運行時函數fopen 打開的C 運行時流式文件。
流式文件是被緩沖的,而且可以以文本方式(預設)或二進制方式打開。文本方式提供對硬回車—換行符對的特殊處理。當你將一個換行符(0x0A)寫入一個文本方式的CStdioFile 對象時,位元組對(0x0D,0x0A)被發送給該文件。當你讀一個文件時,位元組對(0x0D,0x0A)被翻譯為一個位元組(0x0A)。
CStdioFile 不支持Duplicate,LockRange,和UnlockRange 這幾個CFile 函數。如果在CStdioFile 中調用了這幾個函數,將會出現CNoSupported 異常。
使用類CInternetSession 創建並初始化一個或多個同時的Internet 會話。如果需要,還可描述與代理伺服器的連接。
如果Internet連接必須在應用過程中保持著,可創建一個類CWinApp的CInternetSession成員。一旦已建立起Internet 會話,就可調用OpenURL。CInternetSession會通過調用全局函數AfxParseURL來為分析映射URL。無論協議類型如何,CInternetSession 解釋URL並管理它。它可處理由URL資源「file://」標志的本地文件的請求。如果傳給它的名字是本地文件,OpenURL 將返回一個指向CStdioFile對象的指針。
如果使用OpenURL在Internet伺服器上打開一個URL,你可從此處讀取信息。如果要執行定位在伺服器上的指定的服務(例如,HTTP,FTP或Gopher)行為,必須與此伺服器建立適當的連接。
❽ c# c/s結構Socket上傳文件的代碼
發送端(client)
private void button2_Click(object sender, EventArgs e)
{
this.button2.Enabled = false;
Thread TempThread = new Thread(new ThreadStart(this.StartSend));
TempThread.Start();
}private void StartSend()
{
//FileInfo EzoneFile = new FileInfo(this.textBox1.Text);string path = @"E:old F directoryTangWeikangge ew1.jpg";
FileInfo EzoneFile = new FileInfo(path);
FileStream EzoneStream = EzoneFile.OpenRead();
int PacketSize = 100000;
int PacketCount = (int)(EzoneStream.Length / ((long)PacketSize));
// this.textBox8.Text = PacketCount.ToString();
// this.progressBar1.Maximum = PacketCount;
int LastDataPacket = (int)(EzoneStream.Length - ((long)(PacketSize * PacketCount)));
// this.textBox9.Text = LastDataPacket.ToString();
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(ipep);
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(EzoneFile.Name));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketSize.ToString()));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(PacketCount.ToString()));
// TransferFiles.SendVarData(client, System.Text.Encoding.Unicode.GetBytes(LastDataPacket.ToString()));
byte[] data = new byte[PacketSize];
for(int i=0; i<PacketCount; i++)
{
EzoneStream.Read(data, 0, data.Length);TransferFiles.SendVarData(client, data);
// this.textBox10.Text = ((int)(i + 1)).ToString();
// this.progressBar1.PerformStep();
}if(LastDataPacket != 0)
{
data = new byte[LastDataPacket];EzoneStream.Read(data, 0, data.Length);
TransferFiles.SendVarData(client,data);
// this.progressBar1.Value = this.progressBar1.Maximum;
}
client.Close();EzoneStream.Close();
this.button2.Enabled = true;
}接收端(server)
private void button2_Click(object sender, EventArgs e)
{
//int i = 0;
//FileStream recfs = new FileStream("E:\kangge.jpg", FileMode.OpenOrCreate);
//Byte[] recbyte = new Byte[2000000];
//Socket hostsocket = receive.Accept();
//BinaryWriter newfilestr = new BinaryWriter(recfs);
//hostsocket.Receive(recbyte, recbyte.Length, SocketFlags.None);
//for (i = 0; i < recbyte.Length; i++)
//{
// newfilestr.Write(recbyte, i, 1);
//}
//recfs.Close();//hostsocket.Shutdown(SocketShutdown.Receive);
//hostsocket.Close();this.button2.Enabled = false;
Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
TempThread.Start();
}
private void StartReceive()
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("163.180.117.229"), 7000);Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(ipep);
server.Listen(10);
Socket client = server.Accept();
// IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
// string SendFileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
// string BagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
// int bagCount = int.Parse(System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client)));
// string bagLast = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(client));
int file_name = 1;string fileaddr = "E:\old F directory\TangWei\Copy of kangge\" + file_name.ToString() + ".jpg";
FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);// int SendedCount = 0;
while(true)
{
byte[] data = TransferFiles.ReceiveVarData(client);
if(data.Length == 0)
{
break;
}
else
{
// SendedCount++;
MyFileStream.Write(data, 0, data.Length);
}
}MyFileStream.Close();
client.Close();
this.button2.Enabled = true;
}公共類。 TransferFiles
class TransferFiles
{public TransferFiles()
{}
public static int SendVarData(Socket s, byte[] data) // return integer indicate how many data sent.
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);//send the size of data array.while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}return total;
}public static byte[] ReceiveVarData(Socket s) // return array that store the received data.
{
int total = 0;
int recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize, 0, 4, SocketFlags.None);//receive the size of data array for initialize a array.
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data = new byte[size];while (total < size)
{
recv = s.Receive(data, total, dataleft, SocketFlags.None);
if (recv == 0)
{
data = null;
break;
}
total += recv;
dataleft -= recv;
}return data;
}
}
❾ 請教用C語言編的藉助UDP協議實現的文件傳輸的程序
本程序在 Windows 7 Visual Studio 2015 和 Linux Ubuntu 15.04 GCC 5.11 下均編譯運行測試通過。
本程序支持 Windows 和 Linux 之間傳送文件,如果要在 Windows 和 Linux 之間傳送文件,文件名不能出現中文。
本程序支持無線 WiFi,支持 USB 收發器,但僅支持區域網內傳送文件,傳送文件需要輸入對方的 IP 地址。
本程序包括伺服器端和客戶端,既可以發送文件又可以接收文件。如果要在同一台機器上測試需要同時打開兩個程序。
Windows 下查看本機 IP 地址的命令是:
ipconfig
Linux 下查看本機 IP 地址的命令是:
ifconfig
以下是程序代碼:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#ifdef_MSC_VER
#include<winsock2.h>
#include<windows.h>
#pragmacomment(lib,"ws2_32.lib")
#else
#include<pthread.h>
#include<unistd.h>
#include<signal.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#endif
//存放發送接收字元數組大小
#defineSIZEA65501
//每次發送接收位元組數
#defineSIZEB65500
typedefstructsockaddr_inSockAddrIn;
SockAddrInserverAddr,remoteAddr,clientAddr;
//埠號
intiServerPort,iClientPort;
//新建socket信息
intiUDP;
//字元串轉整型
intstrToInt(char*acStr)
{
inti,iIndex=0,iNum=0,iSize=0;
if(acStr[0]=='+'||acStr[0]=='-')
iIndex=1;
for(iSize=iIndex;;iSize++)
if(acStr[iSize]<'0'||acStr[iSize]>'9')
break;
for(i=iIndex;i<iSize;i++)
iNum+=(int)pow(10,iSize-i-1)*(acStr[i]-48);
if(acStr[0]=='-')
iNum=-iNum;
returniNum;
}
//整型轉字元串
voidintToStr(intiInt,char*acStr)
{
intiIndex=0,iSize,iNum,iBit,i,j;
if(iInt<0)
{
acStr[0]='-';
iInt=-iInt;
iIndex=1;
}
for(i=0;;i++)
if(iInt<pow(10,i))
break;
iSize=i;
for(i=0;i<iSize;i++)
{
iNum=pow(10,iSize-i-1);
iBit=iInt/iNum;
iInt-=iNum*iBit;
acStr[i+iIndex]=iBit+48;
}
if(iSize!=0)
acStr[iSize+iIndex]='