簡體   English   中英

從文件中一次讀取X個字符

[英]Reading in from a file X characters at a time in C

我正在嘗試編寫一個程序,該程序允許我從文件中讀取數據,然后使用數據層將其發送到另一個程序,該程序將其寫入另一個文件。 我遇到的問題是,我被限制為100個字符的幀大小,包括一個1個字符的標題和一個稍后將添加的2個字符的CRC值。 這意味着我一次讀取97個字符,然后發送出去,但是我不確定如何只讀取該字符而不是清除字符並重新開始。 我將發布我擁有的代碼,感謝您的幫助。

發送文件

#include <stdio.h>
#define MAXFRAME  97
main(int argc, char* argv[]){
    char *frame;
    int len = 0;
    int c;
    dlinits("spirit.cba.csuohio.edu", 43520);
    frame = malloc(MAXFRAME);

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
        return NULL;

    while ((c = fgetc(file)) != EOF)
    {
        frame[len++] = (char) c;
    }


}

接收檔案

#include <string.h>
char* dlrecv();

main(){
    char* test[100];
    dlinitr(43520);
    strcpy(test,dlrecv());

    printf("%s\n", test);



}

資料層

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#define BUFMAX 100

static int sk;
static struct sockaddr_in remote;
static struct sockaddr_in local;

dlinits(char* host, int port){//initialize sender

    struct hostent *hp;
    sk = socket(AF_INET, SOCK_DGRAM, 0);

    remote.sin_family = AF_INET;

    hp = gethostbyname(host);
    if (hp == NULL){
        printf("Can't find host name\n");
        exit(1);
    }

    bcopy(hp->h_addr,&remote.sin_addr.s_addr,hp->h_length);

    remote.sin_port = ntohs(port);
}

dlinitr(int port){//initialize receiver
    int rlen = sizeof(remote);
    int len = sizeof(local);
    char buf[BUFMAX];

    sk = socket(AF_INET,SOCK_DGRAM,0);

    local.sin_family = AF_INET;
    local.sin_addr.s_addr = INADDR_ANY;
    local.sin_port = htons(port);
    bind (sk, &local,sizeof(local));

    getsockname(sk,&local,&len);

}

dlsend(char* msg, int len){//send data

    printf("%s\n", msg);
    sendto(sk,msg,strlen(msg)+1,0,&remote,sizeof(remote));
} 

char* dlrecv(){//receive data
    char* msg = malloc(sizeof(char) * 100);

    recvfrom(sk,msg,BUFMAX,0,&remote,sizeof(remote));
    printf("%s\n", msg);
    return msg;
}

核心問題是數據輸出不總是97個char (+3開銷),但是每次讀取總是完成97 + 3個char 解決此問題的一些方法是:

1)填充輸出,因此它始終是固定數量的char

2)Receiver尋找可變數量的char來接收,該char具有超前長度值或特殊的終止符,例如\\0

為了簡單起見,建議使用\\0填充。

一切順利之后,請使用第二種方法。


其他小問題:

3)在附加CRC時,每個字節的CRC值范圍從0到255。 這意味着發送/接收方法是二進制而不是文本。 然而,要發送的數據文件以文本模式“ r”打開。 需要注意潛在的EOL文本/二進制轉換問題。 例如使用strlen(msg) 如果msg是整個前導字節+文本+ CRC,這將是一個問題。

4)避免魔術數字。 而是自我記錄下來。

// dlinits("spirit.cba.csuohio.edu", 43520);
// dlinitr(43520);

// In some common header file
#define DATA_LAYER_PORT 43520
dlinits("spirit.cba.csuohio.edu", DATA_LAYER_PORT);
dlinitr(DATA_LAYER_PORT);

5) MAXFRAMEBUFMAX不應獨立定義。

// In some common header file
#define MAXFRAME 100
#define BUFMAX (MAXFRAME - 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM