>백엔드 개발 >C++ >chatGPT - C 프로그래밍 Linux Windows 크로스 플랫폼 - 코드 검토 요청

chatGPT - C 프로그래밍 Linux Windows 크로스 플랫폼 - 코드 검토 요청

Barbara Streisand
Barbara Streisand원래의
2024-11-09 20:35:03954검색

chatGPT - C programming Linux Windows cross-platform - code review request

C로 프로그래밍하기 위해 chatGPT 프롬프트를 사용하는 데 방해가 되었습니다.

증분 프롬프트를 사용하면 chatGPT 3.5에서 예상보다 더 많은 작업을 수행할 수 있습니다.

코드 품질이 궁금합니다. 프롬프트와 코드 모두에 대한 피드백을 받고 싶습니다.

기능 목표

  • 경로가 유효한지 확인하고 경로 구성 요소를 구문 분석하세요
  • MacOS Linux Windows 크로스 플랫폼 호환성

구현

스레드 안전 코드
정적 경로
더 큰 경로 문자열에 대한 동적 경로 할당

Linux/MacOs의 표준 관행은 동적으로 할당(4095/1024 차트 경로 제한)하는 반면 Windows(260 경로 제한)는 정적으로 할당하는 것입니다.

즉각적인

쿼리를 점진적으로 구축합니다. 그렇지 않으면 chatGPT가 이전 요청 변경 사항을 학습하지 않는 경향이 있습니다.

결국 이는 LLM이 원하는 코드를 생성하도록 강제할 수 있는 일종의 조잡한 형태의 메타 코딩처럼 보입니다.

_query
    LLM perplexity.ai

Modify code example
  Portable Path Parsing and Validation Code in C
    use thread safe function
      use function pointer
        strtok_s() for Windows
        strtok_r() for linux
allocate INITIAL_BUFFER_SIZE 60 char static path_copy
  declare pointer pfinal_path_copy initialize to path_copy
      when necessary
          dynamically allocate final_path_copy
          pfinal_path_copy = final_path_copy
use single strcpy(pfinal_path_copy, path) function

코드는 원하는 스타일에 맞게 한 번에 한 기능씩 형성됩니다

modify example 
replace 60 by equate

일부 메시지는 반복되지 않고 계속 유지되었습니다. "WSL cygwin 없음"은 Windows OS 특정 코드를 묻는 메시지를 표시하기 위해 초기에 추가된 후 삭제되었습니다.

write code example
 parse path in portable way
    linux windows MacOS
        no WSL cygwin

암호

결과 코드는 처음부터 컴파일 및 실행됩니다.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef _WIN32
#include <io.h>  // For _access() on Windows
#include <windows.h> // For Windows API
#else
#include <unistd.h>  // For access() on Unix-like systems (Linux, macOS)
#include <sys/stat.h>
#endif

// Define a constant for the initial buffer size
#define INITIAL_BUFFER_SIZE 60

// Function to check if a path is valid
int path_validate(const char *path) {
#ifdef _WIN32
    return _access(path, 0) == 0; // 0 means the file exists
#else
    struct stat buffer;
    return (stat(path, &buffer) == 0); // Returns 1 if valid, 0 if invalid
#endif
}

// Type definition for tokenization function pointer
typedef char* (*tokenizer_func)(char*, const char*, char**);

// Function to parse the path into components
void parse_path(const char *path) {
    char path_copy[INITIAL_BUFFER_SIZE]; // Static buffer for initial use
    char *final_path_copy = NULL; // Pointer for dynamic allocation
    char *pfinal_path_copy = path_copy; // Pointer to point to either path_copy or final_path_copy

    // Check if the input path length exceeds INITIAL_BUFFER_SIZE
    if (strlen(path) + 1 > INITIAL_BUFFER_SIZE) {
        final_path_copy = malloc(strlen(path) + 1); // Dynamically allocate memory
        if (final_path_copy == NULL) {
            fprintf(stderr, "Memory allocation failed.\n");
            exit(EXIT_FAILURE);
        }
        pfinal_path_copy = final_path_copy; // Point to dynamically allocated memory
    }

    // Use a single strcpy function to copy the path into the appropriate buffer
    strcpy(pfinal_path_copy, path); // Copy full path into the selected buffer

    // Determine the separator based on the platform and assign the tokenizer function
    const char *separator;
    tokenizer_func tokenizer;
    char *saveptr;

#ifdef _WIN32
    separator = "\";
    tokenizer = strtok_s; // Use strtok_s for Windows
#else
    separator = "/";
    tokenizer = strtok_r; // Use strtok_r for Linux
#endif

    // Tokenize using the assigned tokenizer function
    char *token = tokenizer(pfinal_path_copy, separator, &saveptr);

    while (token != NULL) {
        printf("Path component: %s\n", token);
        token = tokenizer(NULL, separator, &saveptr); // Continue tokenizing
    }

    free(final_path_copy); // Free dynamically allocated memory after use (if allocated)
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <path>\n", argv[0]);
        return EXIT_FAILURE;
    }

    const char *path = argv[1];

    // Validate the path using the new function name
    if (path_validate(path)) {
        printf("The path '%s' is valid.\n", path);
        printf("Parsing components:\n");
        parse_path(path);
    } else {
        printf("The path '%s' is invalid.\n", path);
    }

    return EXIT_SUCCESS;
}

## Unit test

Was created but not included here

## Performance

The entire exercise took 2:30 hour.
I have not tested the code on Windows or MacOS.
I'd like some feedback on code quality.

위 내용은 chatGPT - C 프로그래밍 Linux Windows 크로스 플랫폼 - 코드 검토 요청의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.