什么是最简单的方法(最不容易出错,最少的代码行,但是你想要解释它)在C中打开一个文件并将其内容读入一个字符串(char*,char [],等等)?
我在将文本转换为char数组时遇到了一些麻烦.当我为数组设置静态大小时,它工作正常
char speech[15000];
Run Code Online (Sandbox Code Playgroud)
但这样效率很低,所以我尝试使用calloc.这使它停止工作.数组的大小合适,但没有任何内容写入.这是相关的代码.我究竟做错了什么?
int main() {
FILE* inFile;
int i;
int count = 0;
printf("\nOpening file April_30_1789.txt\n");
inFile = fopen("./speeches/April_30_1789.txt", "r");
if(inFile == NULL) {
printf("Could not find April_30_1789.txt\n");
return -1;
}
char ch;
while((ch = fgetc(inFile) != EOF)) count++;
rewind(inFile);
int size = count;
printf("Size of the array is %d\n", size);
char *speech = (char *)malloc(size*sizeof(char) + 1*sizeof(char));
fscanf(inFile, "%s", speech);
printf("Closing the file.\n");
fclose(inFile);
printf("%s", speech);
printf("\n\nDone\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
目前,这给了我
Opening file April_30_1789.txt
Size of the …Run Code Online (Sandbox Code Playgroud) 这是一个后续问题
有很多文章和博客提到 Java 和 JVM 指令重新排序,这可能会导致用户操作中出现反直觉的结果。
当我要求演示 Java 指令重新排序导致意外结果时,有几条评论说,更普遍的关注领域是内存重新排序,并且很难在 x86 CPU 上进行演示。
指令重新排序只是内存重新排序、编译器优化和内存模型等更大问题的一部分吗?这些问题真的是 Java 编译器和 JVM 特有的吗?它们是否特定于某些 CPU 类型?
java cpu-architecture memory-barriers instruction-reordering