您好,登錄后才能下訂單哦!
在C語言中,字符串和文件操作可以通過以下方式結(jié)合使用:
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("無法打開文件\n");
return 1;
}
char *buffer = malloc(1024);
if (buffer == NULL) {
printf("內(nèi)存分配失敗\n");
fclose(file);
return 1;
}
while (fgets(buffer, 1024, file)) {
printf("%s", buffer);
}
free(buffer);
fclose(file);
return 0;
}
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("無法打開文件\n");
return 1;
}
const char *str = "Hello, World!\n";
fputs(str, file);
fclose(file);
return 0;
}
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("無法打開文件\n");
return 1;
}
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, file)) != -1) {
printf("%s", line);
}
free(line);
fclose(file);
return 0;
}
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("無法打開文件\n");
return 1;
}
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
return 0;
}
這些示例展示了如何在C語言中使用字符串和文件操作。你可以根據(jù)需要調(diào)整代碼以滿足特定需求。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。