코드에서 외부프로그램 실행 후 결과값 받는것 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define BUFFER_SIZE 1024
 
int main() {
 
    char buffer[BUFFER_SIZE] = {0};
 
    FILE *fp = popen(".//test.exe dir""r");
 
    if(fp == NULL) {
        return -1;
    }
 
    while(fgets(buffer, BUFFER_SIZE, fp)) {
        printf("%s", buffer);
 
        memset(buffer, 0, BUFFER_SIZE);
    }
 
    return 0;
}
cs

 

그리고 외부프로그램 실행 후 명령어 주고 결과 받는 프로그램 

(이건 검증 필요) 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define BUFFER_SIZE 1024
 
int main() {
 
    char buffer[BUFFER_SIZE] = {0};
    int loop_cnt =0;
 
    FILE *fp = popen(".//test.exe aaaa""r");
    FILE *fp2 = popen(".//test.exe bbbb""w");
 
    if(fp == NULL) {
        return -1;
    }
 
    if(fp2 == NULL) {
        return -1;
    }
 
    while(loop_cnt < 3) {
        
        if(loop_cnt ==1 ){
            frpintf(fp2, "1111");
        }else if(loop_cnt == 2){
            fprintf(fp2, "2222");
        }
 
        fgets(buffer,BUFFER_SIZE, fp);
 
        printf("%s \n", buffer );
        memset(buffer, 0, BUFFER_SIZE);
        loop_cnt++;
    }
 
    return 0;
}
 
cs

 

관련 내용은 아래 링크 참고함 

https://www.it-note.kr/4

 

popen(3), pclose(3)의 활용 - 다른 프로세스의 표준 입/출력 제어하기

데몬(daemon) 프로그램이 아닌 이상, 많은 프로그램(명령어)들은 데이터를 keyboard로 입력을 하거나, 그 결과를 화면의 출력으로 확인한다. 그래서 이런 경우에는 사람이 직접 수작업으로 실행하고

www.it-note.kr

 

아래 코드 참고 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/* microhttpd */
 
#include <stdbool.h>
#include <microhttpd.h>
 
#define PORT 8080
#define POSTBUFFERSIZE 512
 
#define GET 0
#define POST 1
 
#define REQUEST_REFUSED_PAGE \
    "<html><head><title> Request refused </title></head><body> Request Refused (file exist?) </body></html>"
 
const char *responseOK = "\"Result\":\"OK\"";
const char *responseExist = "\"Result\":\"Queue Exist\"";
 
struct postStatus {
    bool status;
    char *buff;
};
 
struct NODE {
    struct NODE *next;
    char msg[30];
    int available;
    char idx[5];
};
 
struct MULTI_MSG_QUEUE {
    int cur_size;
    int max_size;
    char name[20];
 
    struct NODE *msgq;
};
 
int cur_multi_queue_cnt =0;
struct MULTI_MSG_QUEUE multi_queue[10= {0};
 
static struct MHD_Response *request_refused_response; 
 
static void request_completed_callback (void *cls, 
                                        struct MHD_Connection *connection,
                                        void **con_cls,
                                        enum MHD_RequestTerminationCode toe)
{
    printf("request_completed_callback \n");
}
 
static enum MHD_Result access_handler_callback ( void * cls, 
                struct MHD_Connection *connection,
                const char *url,
                const char *method,
                const char *version,
                const char *upload_data,
                size_t *upload_data_size, void **con_cls) {
 
    int ret;
    printf("url - %s \n", url);
    printf("method - %s \n", method);
    printf("version - %s \n", version);
    printf("upload_data - %s size - %d \n", upload_data, (int)*upload_data_size);
 
    struct MHD_Response * response;
    char url_cpy[50= {0};
    char cmd_list[3][20= {0};
    int cmd_cnt =0;
    char *str_ptr = NULL;
 
    char queue_size[10={0};
    char queue_message[50= {0};
 
    strcpy(url_cpy,url);
 
    if(url_cpy[0== '/') {
        str_ptr = strtok(&url_cpy[1], "/");
    }else {
        str_ptr = strtok(url_cpy, "/");
    }
 
    while(str_ptr != NULL) {
        strcpy(cmd_list[cmd_cnt], str_ptr);
        str_ptr = strtok(NULL"/");
        cmd_cnt++;
    }
 
    struct postStatus *post = NULL;
    post = (struct postStatus *)*con_cls;
 
    if(post == NULL) {
        post = malloc(sizeof(struct postStatus));
        post->status = false;
        post->buff = NULL;
        *con_cls = post;
    }
 
    printf("post->status = %d \n", post->status);
 
    if(!post->status) {
        post->status = true;
        return MHD_YES;
    }else {
        if(*upload_data_size != 0) {
            post->buff = malloc(*upload_data_size +1);
            memset(post->buff, 0*upload_data_size +1);
 
            strncpy(post->buff, upload_data, *upload_data_size);
            *upload_data_size =0;
            return MHD_YES;
        }else {
            if(strncmp(cmd_list[0], "CREATE",6== 0) {
                json_object *root, *QueueSize;
                root = json_tokener_parse(post->buff);
                json_object_object_get_ex(root, "QueueSize"&QueueSize);
                printf("QueueSize : %s \n", json_object_get_string(QueueSize));
 
                strcpy(queue_size, json_object_get_string(QueueSize));
            }else  if(strncmp(cmd_list[0], "SEND",4== 0) {
                json_object *root, *q_msg;
                root = json_tokener_parse(post->buff);
                json_object_object_get_ex(root, "Message"&q_msg);
                printf("Message : %s \n", json_object_get_string(q_msg));
 
                strcpy(queue_message, json_object_get_string(q_msg));
            }else  if(strncmp(cmd_list[0], "RECEIVE",7== 0) {
                //[no body]
            }
 
            if(post->buff != NULL) {
                free(post->buff);
            }
        }
    }
 
    if(post != NULL) {
        free(post);
    }
 
    json_object *myobj = json_object_new_object();
 
    if(strncmp(cmd_list[0], "CREATE",6== 0) {
 
        int is_exist =0;
 
        for(int i=0; i<cur_multi_queue_cnt; i++) {
            
            if(strncmp(multi_queue[i].name, cmd_list[1], strlne(cmd_list[i]) ) == 0) {
                is_exist =1;
                break;
            }
        }
 
        if(is_exist) {
            printf("Queue Exist \n");
            json_object_object_add(myobj, "Result", json_object_new_string("Queue Exist"));
        }else {
 
            multi_queue[cur_multi_queue_cnt].max_size = atoi(queue_size);
            strcpy(multi_queue[cur_multi_queue_cnt].name = cmd_list[1]);
            multi_queue[cur_multi_queue_cnt].cur_size =0;
 
            multi_queue[cur_multi_queue_cnt].msgq = (struct NODE *)malloc(sizeof(struct NODE));
            multi_queue[cur_multi_queue_cnt].msgq->next = NULL;
            cur_multi_queue_cnt++;
 
            json_object_object_add(myobj, "Result", json_object_new_string("Ok"));
        }
    }else  if(strncmp(cmd_list[0], "SEND",4== 0) {
 
        int q_cnt =-1;
 
        for(int i=0; i<cur_multi_queue_cnt; i++) {
            
            if(strncmp(multi_queue[i].name, cmd_list[1], strlne(cmd_list[i]) ) == 0) {
                q_cnt =i;
                break;
            }
        }
 
        if(q_cnt != -1) {
 
            if(multi_queue[q_cnt].cur_size < multi_queue[q_cnt].max_size) {
 
                struct NODE *new = (struct NODE *)malloc(sizeof(struct NODE));
                char msg_cpy[30={0};
 
                memset(new->msg, 0, siezeof(new->msg));
                new->next = NULL;
 
                strcpy(new->msg, queue_message);
                new->available = 1;
 
                strcpy(msg_cpy,queue_message);
 
                int msg_loop_cnt = 0;
 
                str_ptr = strtok(msg_cpy, "#");
                while(str_ptr != NULL) {
                    if(msg_loop_cnt == 0) {
 
                    }else if(msg_loop_cnt == 1) {
                        strcpy(new->idx, str_ptr);
                    }
 
                    str_ptr = strtok(NULL"#");
                    msg_loop_cnt++;
                }
            }
 
            struct NODE *cur = multi_queuep[q_cnt].msgq;
 
            new->next= cur->next;
            cur->next = new;
 
            multi_queue[q_cnt].cur_size++;
 
            json_object_object_add(myobj, "Result", json_object_new_string("Ok"));
        }else {
            printf("Queue Full \n");
            json_object_object_add(myobj, "Result", json_object_get_string("Queue Full"));
        }
 
    }else  if(strncmp(cmd_list[0], "RECEIVE",7== 0) {
        //similar with SEND 
    }
 
    const char *result_json = json_object_to_json_string_ext(myobj, JSON_C_TO_STRING_PLAIN);
 
    response = MHD_create_response_from_buffer (strlen(result_json), (void *)result_json, 
                                                    MHD_RESPMEM_MUST_COPY);
 
    if(!response) {
        return MHD_NO;
    }
 
    ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
    MHD_destroy_response(response);
 
    return ret; 
}
 
 
int main(int argc, char *argv[]) {
 
    struct MHD_Daemon *daemon = MHD_start_daemon (
                                    MHD_USE_THREAD_PER_CONNECTION,
                                    PORT,                        
                                    NULLNULL,
                                    &access_handler_callback,
                                    NULL,
                                    MHD_OPTION_NOTIFY_COMPLETED,
                                    &request_completed_callback,
                                    NULL,
                                    MHD_OPTION_END);
 
    request_refused_response = MHD_create_response_from_buffer(strlen(REQUEST_REFUSED_PAGE),
                                                            (void *)REQUEST_REFUSED_PAGE,
                                                            MHD_RESPMEM_PERSISTENT);
    if(daemon == NULL) {
        fprintf(stderr, "MHD_start_daemon () error \n");
        return EXIT_FAILURE;
    }
 
    while(true) {
        getc(stdin);
    }
 
    //HTTP 데몬을 종료한다. 
    MHD_stop_daemon(daemon);
 
    MHD_destroy_response(request_refused_response);
 
    return EXIT_SUCCESS;
}
cs

- Get 방식  - 요청/응답 ( "http://127.0.0.1:8080/helloworld")

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <curl/curl.h>
 
void request_get_helloworld(void) {
    CURL *curl;
    CURLcode res;
 
    struct memory data;
    char url[100={0};
 
    memset(&data, 0sizeof(data));
 
    curl = curl_easy_init();
    if(curl) {
        sprintf(url, "http://127.0.0.1:8080/helloworld");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&data);
 
        res = curl_easy_perform(curl);
        if(CURLE_OK == res) {
            long status_code = 0;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code);
 
            printf("[status line] Status Code %ld \n", status_code);
            printf("[body] %s \n", data.response);            
        }else {
            printf("response is not OK : %d \n", res);
        }
    }
 
    /* always cleanup */
    curl_easy_cleanup(curl);
}
cs

- POST 방식 - 요청/응답 ( "http://127.0.0.1:8080/helloworld")

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <curl/curl.h>
 
void request_post_helloworld(void) {
 
   CURL *curl;
   CURLcode res;
 
    struct memory data;
    char url[100={0};
    char post[100={0};
 
    memset(&data, 0sizeof(data));
 
    curl = curl_easy_init();
    if(curl) {
        sprintf(url, "http://127.0.0.1:8080/helloworld");
        sprintf(post, "Hello World");
 
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_POST, 1L); //POST request
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post); //POST request payload
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(post)); //POST request payload size
 
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&data);
 
        res = curl_easy_perform(curl);
        if(CURLE_OK == res) {
            long status_code = 0;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code);
 
            printf("[status line] Status Code %ld \n", status_code);
            printf("[body] %s \n", data.response);            
        }else {
            printf("response is not OK : %d \n", res);
        }
    }
 
    /* always cleanup */
    curl_easy_cleanup(curl);
 
}
cs

'프로그래밍 > C언어' 카테고리의 다른 글

코드에서 외부프로그램 실행  (0) 2022.07.11
Microhttpd 를 이용한 Post 구현  (0) 2022.07.11
Json C로 Json <-> string 변환  (0) 2022.07.11
연결리스트로 스택 만들기  (0) 2022.07.10
연결 리스트로 큐 생성  (0) 2022.07.10

아래 예제를 참고한다. 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <json-c/json.h>
 
json_object *myobj = json_object_new_object();
 
json_object_object_add(myobj,"name", json_object_new_string("KIM"));
json_object_object_add(myobj,"phone", json_object_new_string("01000000000"));
const char *result_json = json_object_to_json_string_next(myobj, JSON_C_TO_STRING_PLAIN);
 
printf("json:L %s \n", result_json);
 
json_object *root, *name, *phone;
root = json_tokener_parse(result_json);
json_object_object_get_ex(root, "name"&name);
json_object_object_get_ex(root, "phone"&phone);
 
printf("name : %s, phone : %s \n", json_object_get_string(name), json_object_get_string(phone));
 
 
cs

'프로그래밍 > C언어' 카테고리의 다른 글

Microhttpd 를 이용한 Post 구현  (0) 2022.07.11
curl 을 이용한 클라이언트 get , post 요청  (0) 2022.07.11
연결리스트로 스택 만들기  (0) 2022.07.10
연결 리스트로 큐 생성  (0) 2022.07.10
Msg Queue  (0) 2022.06.14

아래 링크를 참고했으며, 연결 리스트로 스택을 만듬 

 

https://ehpub.co.kr/c%EC%96%B8%EC%96%B4-%EC%86%8C%EC%8A%A4-%EC%8A%A4%ED%83%9D%EC%9D%84-%EC%97%B0%EA%B2%B0%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A1%9C-%EA%B5%AC%ED%98%84/

 

[C언어 소스] 스택을 연결리스트로 구현 – 언제나 휴일

안녕하세요. 언제나 휴일입니다. 이번에는 스택(STACK)을 연결리스트로 구현하는 소스 코드입니다. 스택은 자료를 한쪽으로 보관하고 꺼내는 LIFO(Last In First Out) 방식의 자료구조입니다. 스택에 자

ehpub.co.kr

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
#include <stdio.h>
#include <stdlib.h>
 
 
typedef struct node {
    int data;
    struct node *next;
}Node;
 
typedef struct stack {
    Node *top;    
}Stack;
 
void InitStack(Stack *stack) {
    stack->top = NULL
}
 
int IsEmpty(Stack *stack) {
    return stack->top == NULL;    
}
 
void Push(Stack *stackint data) {
    Node *now = (Node *)malloc(sizeof(Node)); 
    now->data = data;
    now->next = stack->top;
    stack->top = now;   
}
 
int Pop(Stack *stack) {
    Node *now;
    int re;
    if (IsEmpty(stack))
    {
        return 0;
    }
    now = stack->top;
    re = now->data;
 
    stack->top = now->next;
    free(now);
    return re;
}
 
int main(void) {
    int i;
    Stack stack;
 
    InitStack(&stack);
    for (i = 1; i <= 5; i++)     {
        Push(&stack, i);
    }
 
    while (!IsEmpty(&stack))     {
        printf("%d ", Pop(&stack));
    }
    
    printf("\n");
    return 0;
}
 
 
cs

'프로그래밍 > C언어' 카테고리의 다른 글

curl 을 이용한 클라이언트 get , post 요청  (0) 2022.07.11
Json C로 Json <-> string 변환  (0) 2022.07.11
연결 리스트로 큐 생성  (0) 2022.07.10
Msg Queue  (0) 2022.06.14
파일입출력, 라인단위 읽고쓰기  (0) 2019.07.23

코드의 소스는 아래 링크이며, 처음에 등록된 노드가 앞에 있고, 뒤로 등록된 노드들을 연결함 

 

https://ehpub.co.kr/c%EC%96%B8%EC%96%B4-%EC%86%8C%EC%8A%A4-%EC%8A%A4%ED%83%9D%EC%9D%84-%EC%97%B0%EA%B2%B0%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A1%9C-%EA%B5%AC%ED%98%84/

 

[C언어 소스] 스택을 연결리스트로 구현 – 언제나 휴일

안녕하세요. 언제나 휴일입니다. 이번에는 스택(STACK)을 연결리스트로 구현하는 소스 코드입니다. 스택은 자료를 한쪽으로 보관하고 꺼내는 LIFO(Last In First Out) 방식의 자료구조입니다. 스택에 자

ehpub.co.kr

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
 
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
typedef struct node {
    int data;
    struct node *next;
}Node;
 
typedef struct queue {
    Node *front
    Node *rear; 
    int count;
}Queue;
 
void InitQueue(Queue *queue){
    queue->front = queue->rear = NULL
    queue->count = 0;
}
 
int IsEmpty(Queue *queue){
    return queue->count == 0;    
}
 
void Enqueue(Queue *queueint data){
 
    Node *now = (Node *)malloc(sizeof(Node)); 
    now->data = data;
    now->next = NULL;
 
    if (IsEmpty(queue)) {
        queue->front = now;
    }else {
        queue->rear->next = now;
    }
 
    queue->rear = now;
    queue->count++;
}
 
int Dequeue(Queue *queue) {
    int re = 0;
    Node *now;
 
    if (IsEmpty(queue)) {
        return re;
    }
 
    now = queue->front;
    re = now->data;
    queue->front = now->next;
    free(now);
    queue->count--;
    return re;
}
 
int main(void)
{
    int i;
    Queue queue;
    InitQueue(&queue);
    for (i = 1; i <= 5; i++) {
        Enqueue(&queue, i);
    }
 
    while (!IsEmpty(&queue)) {
        printf("%d ", Dequeue(&queue));
    }
 
    printf("\n");
    return 0;
}
 
 
cs

'프로그래밍 > C언어' 카테고리의 다른 글

Json C로 Json <-> string 변환  (0) 2022.07.11
연결리스트로 스택 만들기  (0) 2022.07.10
Msg Queue  (0) 2022.06.14
파일입출력, 라인단위 읽고쓰기  (0) 2019.07.23
directory 내 파일검색  (0) 2019.07.23

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX 1024

struct message_buffer {
    int msg_type;
    char msg_text[MAX];
};

int read_line(char text[], int n);
void writer(int msg_id);
void reader(int msg_id);

int main() {

    int msg_id;

    pid_t pid; 

    msg_id = msgget(IPC_PRIVATE, 0600);
    if(msg_id == -1) {
        perror("msgget");
    }
    pid = fork();
    switch(pid) {
        case -1:
            perror("fork");
            break;
        case 0:
            reader(msg_id);
            break;
        default:
            writer(msg_id);
            break;
    }

    msgctrl(msg_id, IPC_RMID, NULL);
    return 0;
}

int read_line(char text[], int n) {
    char *ptext; 
    int return_value;
    int length;

    ptext = fgets(text, n, stdin);
    if(ptext == NULL) {
        return_value = EOF;
    }else {
        length = strlen(text);

        if(length > 0 && text[length-1] == '\n') {
            text[length-1] = '\0'; 
        }
        return_value != EOF;
        //return_value != EOF; ??
    }
    return return_value;
}

void writer(int msg_id) {
    struct message_buffer m;
    m.msg_type = 1;

    while(read_line(m.msg_text, MAX) != EOF) {
        int length;
        length = strlen(m.msg_text);

        if(msgsnd(msg_id, &m, length, 0) == -1) {
            perror("msgsnd");
            exit(1);
        }
        if(msgsnd(msg_id, &m, 0, 0) == -1) {
            perror("msgsnd");
            exit(1);
        }
    }
}

void reader(int msg_id) {
    int length, n=0;
    struct message_buffer m;

    while(length = msgrcv(msg_id, &m, MAX,0,0)) {
        n+= length;
    }
    if(length == -1) {
        perror("msgrcv");
        exit(1);
    }
    printf("Received number of bytes ")
}​

'프로그래밍 > C언어' 카테고리의 다른 글

연결리스트로 스택 만들기  (0) 2022.07.10
연결 리스트로 큐 생성  (0) 2022.07.10
파일입출력, 라인단위 읽고쓰기  (0) 2019.07.23
directory 내 파일검색  (0) 2019.07.23
숫자 삽입  (0) 2019.06.27

파일 입출력 기본 함수 및 라인단위 읽고 쓰기 함수 예제

(관련 헤더는 stdio.h) 

#include <stdio.h>
  FILE *rfp = fopen(full_name,"r");
	FILE *wfp = fopen("file.txt","w");

	if(rfp == NULL) {
		printf("rfp -- not open \n");
		return 0;
	}
	if(wfp == NULL) {
		printf("wfp -- not open \n");
		return 0;
	}

	char rbuf[1024] = {0,};
	char wbuf[1024] = {0,};

	while(!feof(rfp)) {
		fgets(rbuf,sizeof(rbuf), rfp);
		strncpy(wbuf,rbuf,strlen(rbuf));
		fputs(wbuf,wfp);

		memset(rbuf,0x00,sizeof(rbuf));
		memset(wbuf,0x00,sizeof(wbuf));
	}
	fclose(rfp);
	fclose(wfp);

 

 

'프로그래밍 > C언어' 카테고리의 다른 글

연결 리스트로 큐 생성  (0) 2022.07.10
Msg Queue  (0) 2022.06.14
directory 내 파일검색  (0) 2019.07.23
숫자 삽입  (0) 2019.06.27
이차원배열  (0) 2019.06.27

특정 디렉토리 내에 포함된 파일 위치를 확인할 때 아래 코드를 참고한다. 

(path: 현재 폴더 위치("./BIGFILE") , file_name : 찾는 파일 명, full_path: 파일위치 최종 경로)

#include <dirent.h>
#include <sys/types.h>

void show_dir_content(char *path, char *file_name, char *full_path) {
	DIR *d = opendir(path);
	if(d==NULL) return;
	struct dirent *dir;

	while((dir = readdir(d)) != NULL)
	{
		if(dir->d_type != DT_DIR) {
			printf("%s\n",dir->d_name);
			if(!strcmp(file_name, dir->d_name)) {
				sprintf(full_path,"%s/%s",path, dir->d_name);
				closedir(d);
				printf("%s\n",full_path);
				return;
			}
		}else if(dir->d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0) //if it is a directory
		{
			char d_path[256];
			sprintf(d_path,"%s/%s",path,dir->d_name);
			show_dir_content(d_path,file_name,full_path);
		}
	}
	closedir(d);
}

'프로그래밍 > C언어' 카테고리의 다른 글

Msg Queue  (0) 2022.06.14
파일입출력, 라인단위 읽고쓰기  (0) 2019.07.23
숫자 삽입  (0) 2019.06.27
이차원배열  (0) 2019.06.27
기타 tip  (0) 2019.05.23

1) 특정 수를 기존 수 앞 뒤에 붙여 넣기 

int digit =0;
int tmpInputData = inputData;
//입력수 자릿수 확인 
while(tmpInputData != 0) {
	digit++;
	tmpInputData /= 10;
}
if(checkNum < 10) newNum = inputData*10 + checkNum;
else {
	int frontNum = checkNum/10;
	int endNum = checkNum%10;
	if(frontNum < endNum) {
		int tmp = frontNum;
		frontNum = endNum;
		endNum = tmp;
	}
	newNum = frontNum*(pow(10,digit+1)) + inputData*10 + endNum; 
}

 

'프로그래밍 > C언어' 카테고리의 다른 글

파일입출력, 라인단위 읽고쓰기  (0) 2019.07.23
directory 내 파일검색  (0) 2019.07.23
이차원배열  (0) 2019.06.27
기타 tip  (0) 2019.05.23
문자/숫자 식별/변환하는 라이브러리 함수 (isdigit, isalpha)  (0) 2019.05.23

+ Recent posts